3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkTarget
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Session\SessionManager
;
27 use Wikimedia\RelPath
;
28 use Wikimedia\WrappedString
;
29 use Wikimedia\WrappedStringList
;
32 * This class should be covered by a general architecture document which does
33 * not exist as of January 2011. This is one of the Core classes and should
34 * be read at least once by any new developers.
36 * This class is used to prepare the final rendering. A skin is then
37 * applied to the output parameters (links, javascript, html, categories ...).
39 * @todo FIXME: Another class handles sending the whole page to the client.
41 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
46 class OutputPage
extends ContextSource
{
47 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
48 protected $mMetatags = [];
51 protected $mLinktags = [];
54 protected $mCanonicalUrl = false;
57 * @var string Should be private - has getter and setter. Contains
59 public $mPagetitle = '';
62 * @var string Contains all of the "<body>" content. Should be private we
63 * got set/get accessors and the append() method.
65 public $mBodytext = '';
67 /** @var string Stores contents of "<title>" tag */
68 private $mHTMLtitle = '';
71 * @var bool Is the displayed content related to the source of the
72 * corresponding wiki article.
74 private $mIsarticle = false;
76 /** @var bool Stores "article flag" toggle. */
77 private $mIsArticleRelated = true;
80 * @var bool We have to set isPrintable(). Some pages should
81 * never be printed (ex: redirections).
83 private $mPrintable = false;
86 * @var array Contains the page subtitle. Special pages usually have some
87 * links here. Don't confuse with site subtitle added by skins.
89 private $mSubtitle = [];
92 public $mRedirect = '';
95 protected $mStatusCode;
98 * @var string Used for sending cache control.
99 * The whole caching system should probably be moved into its own class.
101 protected $mLastModified = '';
104 protected $mCategoryLinks = [];
107 protected $mCategories = [
113 protected $mIndicators = [];
115 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
116 private $mLanguageLinks = [];
119 * Used for JavaScript (predates ResourceLoader)
120 * @todo We should split JS / CSS.
121 * mScripts content is inserted as is in "<head>" by Skin. This might
122 * contain either a link to a stylesheet or inline CSS.
124 private $mScripts = '';
126 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
127 protected $mInlineStyles = '';
130 * @var string Used by skin template.
131 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
133 public $mPageLinkTitle = '';
135 /** @var array Array of elements in "<head>". Parser might add its own headers! */
136 protected $mHeadItems = [];
138 /** @var array Additional <body> classes; there are also <body> classes from other sources */
139 protected $mAdditionalBodyClasses = [];
142 protected $mModules = [];
145 protected $mModuleScripts = [];
148 protected $mModuleStyles = [];
150 /** @var ResourceLoader */
151 protected $mResourceLoader;
153 /** @var ResourceLoaderClientHtml */
156 /** @var ResourceLoaderContext */
157 private $rlClientContext;
160 private $rlExemptStyleModules;
163 protected $mJsConfigVars = [];
166 protected $mTemplateIds = [];
169 protected $mImageTimeKeys = [];
172 public $mRedirectCode = '';
174 protected $mFeedLinksAppendQuery = null;
177 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
178 * @see ResourceLoaderModule::$origin
179 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
181 protected $mAllowedModules = [
182 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
185 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
186 protected $mDoNothing = false;
191 protected $mContainsNewMagic = 0;
194 * lazy initialised, use parserOptions()
197 protected $mParserOptions = null;
200 * Handles the Atom / RSS links.
201 * We probably only support Atom in 2011.
202 * @see $wgAdvertisedFeedTypes
204 private $mFeedLinks = [];
206 // Gwicke work on squid caching? Roughly from 2003.
207 protected $mEnableClientCache = true;
209 /** @var bool Flag if output should only contain the body of the article. */
210 private $mArticleBodyOnly = false;
213 protected $mNewSectionLink = false;
216 protected $mHideNewSectionLink = false;
219 * @var bool Comes from the parser. This was probably made to load CSS/JS
220 * only if we had "<gallery>". Used directly in CategoryPage.php.
221 * Looks like ResourceLoader can replace this.
223 public $mNoGallery = false;
226 private $mPageTitleActionText = '';
228 /** @var int Cache stuff. Looks like mEnableClientCache */
229 protected $mCdnMaxage = 0;
230 /** @var int Upper limit on mCdnMaxage */
231 protected $mCdnMaxageLimit = INF
;
234 * @var bool Controls if anti-clickjacking / frame-breaking headers will
235 * be sent. This should be done for pages where edit actions are possible.
236 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
238 protected $mPreventClickjacking = true;
240 /** @var int To include the variable {{REVISIONID}} */
241 private $mRevisionId = null;
244 private $mRevisionTimestamp = null;
247 protected $mFileVersion = null;
250 * @var array An array of stylesheet filenames (relative from skins path),
251 * with options for CSS media, IE conditions, and RTL/LTR direction.
252 * For internal use; add settings in the skin via $this->addStyle()
254 * Style again! This seems like a code duplication since we already have
255 * mStyles. This is what makes Open Source amazing.
257 protected $styles = [];
259 private $mIndexPolicy = 'index';
260 private $mFollowPolicy = 'follow';
261 private $mVaryHeader = [
262 'Accept-Encoding' => [ 'match=gzip' ],
266 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
271 private $mRedirectedFrom = null;
274 * Additional key => value data
276 private $mProperties = [];
279 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
281 private $mTarget = null;
284 * @var bool Whether parser output contains a table of contents
286 private $mEnableTOC = false;
289 * @var string|null The URL to send in a <link> element with rel=license
291 private $copyrightUrl;
293 /** @var array Profiling data */
294 private $limitReportJSData = [];
296 /** @var array Map Title to Content */
297 private $contentOverrides = [];
299 /** @var callable[] */
300 private $contentOverrideCallbacks = [];
303 * Link: header contents
305 private $mLinkHeader = [];
308 * @var string The nonce for Content-Security-Policy
313 * Constructor for OutputPage. This should not be called directly.
314 * Instead a new RequestContext should be created and it will implicitly create
315 * a OutputPage tied to that context.
316 * @param IContextSource $context
318 function __construct( IContextSource
$context ) {
319 $this->setContext( $context );
323 * Redirect to $url rather than displaying the normal page
326 * @param string $responsecode HTTP status code
328 public function redirect( $url, $responsecode = '302' ) {
329 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
330 $this->mRedirect
= str_replace( "\n", '', $url );
331 $this->mRedirectCode
= $responsecode;
335 * Get the URL to redirect to, or an empty string if not redirect URL set
339 public function getRedirect() {
340 return $this->mRedirect
;
344 * Set the copyright URL to send with the output.
345 * Empty string to omit, null to reset.
349 * @param string|null $url
351 public function setCopyrightUrl( $url ) {
352 $this->copyrightUrl
= $url;
356 * Set the HTTP status code to send with the output.
358 * @param int $statusCode
360 public function setStatusCode( $statusCode ) {
361 $this->mStatusCode
= $statusCode;
365 * Add a new "<meta>" tag
366 * To add an http-equiv meta tag, precede the name with "http:"
368 * @param string $name Name of the meta tag
369 * @param string $val Value of the meta tag
371 function addMeta( $name, $val ) {
372 array_push( $this->mMetatags
, [ $name, $val ] );
376 * Returns the current <meta> tags
381 public function getMetaTags() {
382 return $this->mMetatags
;
386 * Add a new \<link\> tag to the page header.
388 * Note: use setCanonicalUrl() for rel=canonical.
390 * @param array $linkarr Associative array of attributes.
392 function addLink( array $linkarr ) {
393 array_push( $this->mLinktags
, $linkarr );
397 * Returns the current <link> tags
402 public function getLinkTags() {
403 return $this->mLinktags
;
407 * Add a new \<link\> with "rel" attribute set to "meta"
409 * @param array $linkarr Associative array mapping attribute names to their
410 * values, both keys and values will be escaped, and the
411 * "rel" attribute will be automatically added
413 function addMetadataLink( array $linkarr ) {
414 $linkarr['rel'] = $this->getMetadataAttribute();
415 $this->addLink( $linkarr );
419 * Set the URL to be used for the <link rel=canonical>. This should be used
420 * in preference to addLink(), to avoid duplicate link tags.
423 function setCanonicalUrl( $url ) {
424 $this->mCanonicalUrl
= $url;
428 * Returns the URL to be used for the <link rel=canonical> if
432 * @return bool|string
434 public function getCanonicalUrl() {
435 return $this->mCanonicalUrl
;
439 * Get the value of the "rel" attribute for metadata links
443 public function getMetadataAttribute() {
444 # note: buggy CC software only reads first "meta" link
445 static $haveMeta = false;
447 return 'alternate meta';
455 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
456 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
459 * @param string $script Raw HTML
461 function addScript( $script ) {
462 $this->mScripts
.= $script;
466 * Add a JavaScript file to be loaded as `<script>` on this page.
468 * Internal use only. Use OutputPage::addModules() if possible.
470 * @param string $file URL to file (absolute path, protocol-relative, or full url)
471 * @param string $unused Previously used to change the cache-busting query parameter
473 public function addScriptFile( $file, $unused = null ) {
474 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
475 // This is not an absolute path, protocol-relative url, or full scheme url,
476 // presumed to be an old call intended to include a file from /w/skins/common,
477 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
478 wfDeprecated( __METHOD__
, '1.24' );
481 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
485 * Add a self-contained script tag with the given contents
486 * Internal use only. Use OutputPage::addModules() if possible.
488 * @param string $script JavaScript text, no script tags
490 public function addInlineScript( $script ) {
491 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
495 * Filter an array of modules to remove insufficiently trustworthy members, and modules
496 * which are no longer registered (eg a page is cached before an extension is disabled)
497 * @param array $modules
498 * @param string|null $position Unused
499 * @param string $type
502 protected function filterModules( array $modules, $position = null,
503 $type = ResourceLoaderModule
::TYPE_COMBINED
505 $resourceLoader = $this->getResourceLoader();
506 $filteredModules = [];
507 foreach ( $modules as $val ) {
508 $module = $resourceLoader->getModule( $val );
509 if ( $module instanceof ResourceLoaderModule
510 && $module->getOrigin() <= $this->getAllowedModules( $type )
512 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
513 $this->warnModuleTargetFilter( $module->getName() );
516 $filteredModules[] = $val;
519 return $filteredModules;
522 private function warnModuleTargetFilter( $moduleName ) {
523 static $warnings = [];
524 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
527 $warnings[$this->mTarget
][$moduleName] = true;
528 $this->getResourceLoader()->getLogger()->debug(
529 'Module "{module}" not loadable on target "{target}".',
531 'module' => $moduleName,
532 'target' => $this->mTarget
,
538 * Get the list of modules to include on this page
540 * @param bool $filter Whether to filter out insufficiently trustworthy modules
541 * @param string|null $position Unused
542 * @param string $param
543 * @param string $type
544 * @return array Array of module names
546 public function getModules( $filter = false, $position = null, $param = 'mModules',
547 $type = ResourceLoaderModule
::TYPE_COMBINED
549 $modules = array_values( array_unique( $this->$param ) );
551 ?
$this->filterModules( $modules, null, $type )
556 * Load one or more ResourceLoader modules on this page.
558 * @param string|array $modules Module name (string) or array of module names
560 public function addModules( $modules ) {
561 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
565 * Get the list of script-only modules to load on this page.
567 * @param bool $filter
568 * @param string|null $position Unused
569 * @return array Array of module names
571 public function getModuleScripts( $filter = false, $position = null ) {
572 return $this->getModules( $filter, null, 'mModuleScripts',
573 ResourceLoaderModule
::TYPE_SCRIPTS
578 * Load the scripts of one or more ResourceLoader modules, on this page.
580 * This method exists purely to provide the legacy behaviour of loading
581 * a module's scripts in the global scope, and without dependency resolution.
582 * See <https://phabricator.wikimedia.org/T188689>.
584 * @deprecated since 1.31 Use addModules() instead.
585 * @param string|array $modules Module name (string) or array of module names
587 public function addModuleScripts( $modules ) {
588 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
592 * Get the list of style-only modules to load on this page.
594 * @param bool $filter
595 * @param string|null $position Unused
596 * @return array Array of module names
598 public function getModuleStyles( $filter = false, $position = null ) {
599 return $this->getModules( $filter, null, 'mModuleStyles',
600 ResourceLoaderModule
::TYPE_STYLES
605 * Load the styles of one or more ResourceLoader modules on this page.
607 * Module styles added through this function will be loaded as a stylesheet,
608 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
609 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
611 * @param string|array $modules Module name (string) or array of module names
613 public function addModuleStyles( $modules ) {
614 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
618 * @return null|string ResourceLoader target
620 public function getTarget() {
621 return $this->mTarget
;
625 * Sets ResourceLoader target for load.php links. If null, will be omitted
627 * @param string|null $target
629 public function setTarget( $target ) {
630 $this->mTarget
= $target;
634 * Add a mapping from a LinkTarget to a Content, for things like page preview.
635 * @see self::addContentOverrideCallback()
637 * @param LinkTarget $target
638 * @param Content $content
640 public function addContentOverride( LinkTarget
$target, Content
$content ) {
641 if ( !$this->contentOverrides
) {
642 // Register a callback for $this->contentOverrides on the first call
643 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
644 $key = $target->getNamespace() . ':' . $target->getDBkey();
645 return $this->contentOverrides
[$key] ??
null;
649 $key = $target->getNamespace() . ':' . $target->getDBkey();
650 $this->contentOverrides
[$key] = $content;
654 * Add a callback for mapping from a Title to a Content object, for things
656 * @see ResourceLoaderContext::getContentOverrideCallback()
658 * @param callable $callback
660 public function addContentOverrideCallback( callable
$callback ) {
661 $this->contentOverrideCallbacks
[] = $callback;
665 * Get an array of head items
669 function getHeadItemsArray() {
670 return $this->mHeadItems
;
674 * Add or replace a head item to the output
676 * Whenever possible, use more specific options like ResourceLoader modules,
677 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
678 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
679 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
680 * This would be your very LAST fallback.
682 * @param string $name Item name
683 * @param string $value Raw HTML
685 public function addHeadItem( $name, $value ) {
686 $this->mHeadItems
[$name] = $value;
690 * Add one or more head items to the output
693 * @param string|string[] $values Raw HTML
695 public function addHeadItems( $values ) {
696 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
700 * Check if the header item $name is already set
702 * @param string $name Item name
705 public function hasHeadItem( $name ) {
706 return isset( $this->mHeadItems
[$name] );
710 * Add a class to the <body> element
713 * @param string|string[] $classes One or more classes to add
715 public function addBodyClasses( $classes ) {
716 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
720 * Set whether the output should only contain the body of the article,
721 * without any skin, sidebar, etc.
722 * Used e.g. when calling with "action=render".
724 * @param bool $only Whether to output only the body of the article
726 public function setArticleBodyOnly( $only ) {
727 $this->mArticleBodyOnly
= $only;
731 * Return whether the output will contain only the body of the article
735 public function getArticleBodyOnly() {
736 return $this->mArticleBodyOnly
;
740 * Set an additional output property
743 * @param string $name
744 * @param mixed $value
746 public function setProperty( $name, $value ) {
747 $this->mProperties
[$name] = $value;
751 * Get an additional output property
754 * @param string $name
755 * @return mixed Property value or null if not found
757 public function getProperty( $name ) {
758 return $this->mProperties
[$name] ??
null;
762 * checkLastModified tells the client to use the client-cached page if
763 * possible. If successful, the OutputPage is disabled so that
764 * any future call to OutputPage->output() have no effect.
766 * Side effect: sets mLastModified for Last-Modified header
768 * @param string $timestamp
770 * @return bool True if cache-ok headers was sent.
772 public function checkLastModified( $timestamp ) {
773 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
774 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
777 $config = $this->getConfig();
778 if ( !$config->get( 'CachePages' ) ) {
779 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
783 $timestamp = wfTimestamp( TS_MW
, $timestamp );
785 'page' => $timestamp,
786 'user' => $this->getUser()->getTouched(),
787 'epoch' => $config->get( 'CacheEpoch' )
789 if ( $config->get( 'UseSquid' ) ) {
790 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
792 $config->get( 'SquidMaxage' )
795 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
797 $maxModified = max( $modifiedTimes );
798 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
800 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
801 if ( $clientHeader === false ) {
802 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
806 # IE sends sizes after the date like this:
807 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
808 # this breaks strtotime().
809 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
811 Wikimedia\
suppressWarnings(); // E_STRICT system time bitching
812 $clientHeaderTime = strtotime( $clientHeader );
813 Wikimedia\restoreWarnings
();
814 if ( !$clientHeaderTime ) {
816 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
819 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
823 foreach ( $modifiedTimes as $name => $value ) {
824 if ( $info !== '' ) {
827 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
830 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
831 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
832 wfDebug( __METHOD__
. ": effective Last-Modified: " .
833 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
834 if ( $clientHeaderTime < $maxModified ) {
835 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
840 # Give a 304 Not Modified response code and disable body output
841 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
842 ini_set( 'zlib.output_compression', 0 );
843 $this->getRequest()->response()->statusHeader( 304 );
844 $this->sendCacheControl();
847 // Don't output a compressed blob when using ob_gzhandler;
848 // it's technically against HTTP spec and seems to confuse
849 // Firefox when the response gets split over two packets.
850 wfClearOutputBuffers();
856 * @param int $reqTime Time of request (eg. now)
857 * @param int $maxAge Cache TTL in seconds
858 * @return int Timestamp
860 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
861 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
862 // because even if the wiki page content hasn't changed since, static
863 // resources may have changed (skin HTML, interface messages, urls, etc.)
864 // and must roll-over in a timely manner (T46570)
865 return $reqTime - $maxAge;
869 * Override the last modified timestamp
871 * @param string $timestamp New timestamp, in a format readable by
874 public function setLastModified( $timestamp ) {
875 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
879 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
881 * @param string $policy The literal string to output as the contents of
882 * the meta tag. Will be parsed according to the spec and output in
886 public function setRobotPolicy( $policy ) {
887 $policy = Article
::formatRobotPolicy( $policy );
889 if ( isset( $policy['index'] ) ) {
890 $this->setIndexPolicy( $policy['index'] );
892 if ( isset( $policy['follow'] ) ) {
893 $this->setFollowPolicy( $policy['follow'] );
898 * Set the index policy for the page, but leave the follow policy un-
901 * @param string $policy Either 'index' or 'noindex'.
904 public function setIndexPolicy( $policy ) {
905 $policy = trim( $policy );
906 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
907 $this->mIndexPolicy
= $policy;
912 * Set the follow policy for the page, but leave the index policy un-
915 * @param string $policy Either 'follow' or 'nofollow'.
918 public function setFollowPolicy( $policy ) {
919 $policy = trim( $policy );
920 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
921 $this->mFollowPolicy
= $policy;
926 * Set the new value of the "action text", this will be added to the
927 * "HTML title", separated from it with " - ".
929 * @param string $text New value of the "action text"
931 public function setPageTitleActionText( $text ) {
932 $this->mPageTitleActionText
= $text;
936 * Get the value of the "action text"
940 public function getPageTitleActionText() {
941 return $this->mPageTitleActionText
;
945 * "HTML title" means the contents of "<title>".
946 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
948 * @param string|Message $name
950 public function setHTMLTitle( $name ) {
951 if ( $name instanceof Message
) {
952 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
954 $this->mHTMLtitle
= $name;
959 * Return the "HTML title", i.e. the content of the "<title>" tag.
963 public function getHTMLTitle() {
964 return $this->mHTMLtitle
;
968 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
972 public function setRedirectedFrom( $t ) {
973 $this->mRedirectedFrom
= $t;
977 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
978 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
979 * but not bad tags like \<script\>. This function automatically sets
980 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
981 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
982 * good tags like \<i\> will be dropped entirely.
984 * @param string|Message $name
986 public function setPageTitle( $name ) {
987 if ( $name instanceof Message
) {
988 $name = $name->setContext( $this->getContext() )->text();
991 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
992 # but leave "<i>foobar</i>" alone
993 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
994 $this->mPagetitle
= $nameWithTags;
996 # change "<i>foo&bar</i>" to "foo&bar"
998 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
999 ->inContentLanguage()
1004 * Return the "page title", i.e. the content of the \<h1\> tag.
1008 public function getPageTitle() {
1009 return $this->mPagetitle
;
1013 * Set the Title object to use
1017 public function setTitle( Title
$t ) {
1018 $this->getContext()->setTitle( $t );
1022 * Replace the subtitle with $str
1024 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1026 public function setSubtitle( $str ) {
1027 $this->clearSubtitle();
1028 $this->addSubtitle( $str );
1032 * Add $str to the subtitle
1034 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1036 public function addSubtitle( $str ) {
1037 if ( $str instanceof Message
) {
1038 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1040 $this->mSubtitle
[] = $str;
1045 * Build message object for a subtitle containing a backlink to a page
1047 * @param Title $title Title to link to
1048 * @param array $query Array of additional parameters to include in the link
1052 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1053 if ( $title->isRedirect() ) {
1054 $query['redirect'] = 'no';
1056 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1057 return wfMessage( 'backlinksubtitle' )
1058 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1062 * Add a subtitle containing a backlink to a page
1064 * @param Title $title Title to link to
1065 * @param array $query Array of additional parameters to include in the link
1067 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1068 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1072 * Clear the subtitles
1074 public function clearSubtitle() {
1075 $this->mSubtitle
= [];
1083 public function getSubtitle() {
1084 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1088 * Set the page as printable, i.e. it'll be displayed with all
1089 * print styles included
1091 public function setPrintable() {
1092 $this->mPrintable
= true;
1096 * Return whether the page is "printable"
1100 public function isPrintable() {
1101 return $this->mPrintable
;
1105 * Disable output completely, i.e. calling output() will have no effect
1107 public function disable() {
1108 $this->mDoNothing
= true;
1112 * Return whether the output will be completely disabled
1116 public function isDisabled() {
1117 return $this->mDoNothing
;
1121 * Show an "add new section" link?
1125 public function showNewSectionLink() {
1126 return $this->mNewSectionLink
;
1130 * Forcibly hide the new section link?
1134 public function forceHideNewSectionLink() {
1135 return $this->mHideNewSectionLink
;
1139 * Add or remove feed links in the page header
1140 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1141 * for the new version
1142 * @see addFeedLink()
1144 * @param bool $show True: add default feeds, false: remove all feeds
1146 public function setSyndicated( $show = true ) {
1148 $this->setFeedAppendQuery( false );
1150 $this->mFeedLinks
= [];
1155 * Add default feeds to the page header
1156 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1157 * for the new version
1158 * @see addFeedLink()
1160 * @param string $val Query to append to feed links or false to output
1163 public function setFeedAppendQuery( $val ) {
1164 $this->mFeedLinks
= [];
1166 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1167 $query = "feed=$type";
1168 if ( is_string( $val ) ) {
1169 $query .= '&' . $val;
1171 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1176 * Add a feed link to the page header
1178 * @param string $format Feed type, should be a key of $wgFeedClasses
1179 * @param string $href URL
1181 public function addFeedLink( $format, $href ) {
1182 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1183 $this->mFeedLinks
[$format] = $href;
1188 * Should we output feed links for this page?
1191 public function isSyndicated() {
1192 return count( $this->mFeedLinks
) > 0;
1196 * Return URLs for each supported syndication format for this page.
1197 * @return array Associating format keys with URLs
1199 public function getSyndicationLinks() {
1200 return $this->mFeedLinks
;
1204 * Will currently always return null
1208 public function getFeedAppendQuery() {
1209 return $this->mFeedLinksAppendQuery
;
1213 * Set whether the displayed content is related to the source of the
1214 * corresponding article on the wiki
1215 * Setting true will cause the change "article related" toggle to true
1219 public function setArticleFlag( $v ) {
1220 $this->mIsarticle
= $v;
1222 $this->mIsArticleRelated
= $v;
1227 * Return whether the content displayed page is related to the source of
1228 * the corresponding article on the wiki
1232 public function isArticle() {
1233 return $this->mIsarticle
;
1237 * Set whether this page is related an article on the wiki
1238 * Setting false will cause the change of "article flag" toggle to false
1242 public function setArticleRelated( $v ) {
1243 $this->mIsArticleRelated
= $v;
1245 $this->mIsarticle
= false;
1250 * Return whether this page is related an article on the wiki
1254 public function isArticleRelated() {
1255 return $this->mIsArticleRelated
;
1259 * Add new language links
1261 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1262 * (e.g. 'fr:Test page')
1264 public function addLanguageLinks( array $newLinkArray ) {
1265 $this->mLanguageLinks +
= $newLinkArray;
1269 * Reset the language links and add new language links
1271 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1272 * (e.g. 'fr:Test page')
1274 public function setLanguageLinks( array $newLinkArray ) {
1275 $this->mLanguageLinks
= $newLinkArray;
1279 * Get the list of language links
1281 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1283 public function getLanguageLinks() {
1284 return $this->mLanguageLinks
;
1288 * Add an array of categories, with names in the keys
1290 * @param array $categories Mapping category name => sort key
1292 public function addCategoryLinks( array $categories ) {
1295 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1299 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1301 # Set all the values to 'normal'.
1302 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1304 # Mark hidden categories
1305 foreach ( $res as $row ) {
1306 if ( isset( $row->pp_value
) ) {
1307 $categories[$row->page_title
] = 'hidden';
1311 // Avoid PHP 7.1 warning of passing $this by reference
1312 $outputPage = $this;
1313 # Add the remaining categories to the skin
1315 'OutputPageMakeCategoryLinks',
1316 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1318 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1319 foreach ( $categories as $category => $type ) {
1320 // array keys will cast numeric category names to ints, so cast back to string
1321 $category = (string)$category;
1322 $origcategory = $category;
1323 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1327 $wgContLang->findVariantLink( $category, $title, true );
1328 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1331 $text = $wgContLang->convertHtml( $title->getText() );
1332 $this->mCategories
[$type][] = $title->getText();
1333 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1339 * @param array $categories
1340 * @return bool|ResultWrapper
1342 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1343 # Add the links to a LinkBatch
1344 $arr = [ NS_CATEGORY
=> $categories ];
1345 $lb = new LinkBatch
;
1346 $lb->setArray( $arr );
1348 # Fetch existence plus the hiddencat property
1349 $dbr = wfGetDB( DB_REPLICA
);
1350 $fields = array_merge(
1351 LinkCache
::getSelectFields(),
1352 [ 'page_namespace', 'page_title', 'pp_value' ]
1355 $res = $dbr->select( [ 'page', 'page_props' ],
1357 $lb->constructSet( 'page', $dbr ),
1360 [ 'page_props' => [ 'LEFT JOIN', [
1361 'pp_propname' => 'hiddencat',
1366 # Add the results to the link cache
1367 $lb->addResultToCache( LinkCache
::singleton(), $res );
1373 * Reset the category links (but not the category list) and add $categories
1375 * @param array $categories Mapping category name => sort key
1377 public function setCategoryLinks( array $categories ) {
1378 $this->mCategoryLinks
= [];
1379 $this->addCategoryLinks( $categories );
1383 * Get the list of category links, in a 2-D array with the following format:
1384 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1385 * hidden categories) and $link a HTML fragment with a link to the category
1390 public function getCategoryLinks() {
1391 return $this->mCategoryLinks
;
1395 * Get the list of category names this page belongs to.
1397 * @param string $type The type of categories which should be returned. Possible values:
1398 * * all: all categories of all types
1399 * * hidden: only the hidden categories
1400 * * normal: all categories, except hidden categories
1401 * @return array Array of strings
1403 public function getCategories( $type = 'all' ) {
1404 if ( $type === 'all' ) {
1405 $allCategories = [];
1406 foreach ( $this->mCategories
as $categories ) {
1407 $allCategories = array_merge( $allCategories, $categories );
1409 return $allCategories;
1411 if ( !isset( $this->mCategories
[$type] ) ) {
1412 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1414 return $this->mCategories
[$type];
1418 * Add an array of indicators, with their identifiers as array
1419 * keys and HTML contents as values.
1421 * In case of duplicate keys, existing values are overwritten.
1423 * @param array $indicators
1426 public function setIndicators( array $indicators ) {
1427 $this->mIndicators
= $indicators +
$this->mIndicators
;
1428 // Keep ordered by key
1429 ksort( $this->mIndicators
);
1433 * Get the indicators associated with this page.
1435 * The array will be internally ordered by item keys.
1437 * @return array Keys: identifiers, values: HTML contents
1440 public function getIndicators() {
1441 return $this->mIndicators
;
1445 * Adds help link with an icon via page indicators.
1446 * Link target can be overridden by a local message containing a wikilink:
1447 * the message key is: lowercase action or special page name + '-helppage'.
1448 * @param string $to Target MediaWiki.org page title or encoded URL.
1449 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1452 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1453 $this->addModuleStyles( 'mediawiki.helplink' );
1454 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1456 if ( $overrideBaseUrl ) {
1459 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1460 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1463 $link = Html
::rawElement(
1467 'target' => '_blank',
1468 'class' => 'mw-helplink',
1473 $this->setIndicators( [ 'mw-helplink' => $link ] );
1477 * Do not allow scripts which can be modified by wiki users to load on this page;
1478 * only allow scripts bundled with, or generated by, the software.
1479 * Site-wide styles are controlled by a config setting, since they can be
1480 * used to create a custom skin/theme, but not user-specific ones.
1482 * @todo this should be given a more accurate name
1484 public function disallowUserJs() {
1485 $this->reduceAllowedModules(
1486 ResourceLoaderModule
::TYPE_SCRIPTS
,
1487 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1490 // Site-wide styles are controlled by a config setting, see T73621
1491 // for background on why. User styles are never allowed.
1492 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1493 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1495 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1497 $this->reduceAllowedModules(
1498 ResourceLoaderModule
::TYPE_STYLES
,
1504 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1505 * @see ResourceLoaderModule::$origin
1506 * @param string $type ResourceLoaderModule TYPE_ constant
1507 * @return int ResourceLoaderModule ORIGIN_ class constant
1509 public function getAllowedModules( $type ) {
1510 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1511 return min( array_values( $this->mAllowedModules
) );
1513 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1518 * Limit the highest level of CSS/JS untrustworthiness allowed.
1520 * If passed the same or a higher level than the current level of untrustworthiness set, the
1521 * level will remain unchanged.
1523 * @param string $type
1524 * @param int $level ResourceLoaderModule class constant
1526 public function reduceAllowedModules( $type, $level ) {
1527 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1531 * Prepend $text to the body HTML
1533 * @param string $text HTML
1535 public function prependHTML( $text ) {
1536 $this->mBodytext
= $text . $this->mBodytext
;
1540 * Append $text to the body HTML
1542 * @param string $text HTML
1544 public function addHTML( $text ) {
1545 $this->mBodytext
.= $text;
1549 * Shortcut for adding an Html::element via addHTML.
1553 * @param string $element
1554 * @param array $attribs
1555 * @param string $contents
1557 public function addElement( $element, array $attribs = [], $contents = '' ) {
1558 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1562 * Clear the body HTML
1564 public function clearHTML() {
1565 $this->mBodytext
= '';
1571 * @return string HTML
1573 public function getHTML() {
1574 return $this->mBodytext
;
1578 * Get/set the ParserOptions object to use for wikitext parsing
1580 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1581 * current ParserOption object. This parameter is deprecated since 1.31.
1582 * @return ParserOptions
1584 public function parserOptions( $options = null ) {
1585 if ( $options !== null ) {
1586 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1589 if ( $options !== null && !empty( $options->isBogus
) ) {
1590 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1591 // been changed somehow, and keep it if so.
1592 $anonPO = ParserOptions
::newFromAnon();
1593 $anonPO->setAllowUnsafeRawHtml( false );
1594 if ( !$options->matches( $anonPO ) ) {
1595 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1596 $options->isBogus
= false;
1600 if ( !$this->mParserOptions
) {
1601 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1602 // $wgUser isn't unstubbable yet, so don't try to get a
1603 // ParserOptions for it. And don't cache this ParserOptions
1605 $po = ParserOptions
::newFromAnon();
1606 $po->setAllowUnsafeRawHtml( false );
1607 $po->isBogus
= true;
1608 if ( $options !== null ) {
1609 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1614 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1615 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1618 if ( $options !== null && !empty( $options->isBogus
) ) {
1619 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1621 return wfSetVar( $this->mParserOptions
, null, true );
1623 return wfSetVar( $this->mParserOptions
, $options );
1628 * Set the revision ID which will be seen by the wiki text parser
1629 * for things such as embedded {{REVISIONID}} variable use.
1631 * @param int|null $revid An positive integer, or null
1632 * @return mixed Previous value
1634 public function setRevisionId( $revid ) {
1635 $val = is_null( $revid ) ?
null : intval( $revid );
1636 return wfSetVar( $this->mRevisionId
, $val );
1640 * Get the displayed revision ID
1644 public function getRevisionId() {
1645 return $this->mRevisionId
;
1649 * Set the timestamp of the revision which will be displayed. This is used
1650 * to avoid a extra DB call in Skin::lastModified().
1652 * @param string|null $timestamp
1653 * @return mixed Previous value
1655 public function setRevisionTimestamp( $timestamp ) {
1656 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1660 * Get the timestamp of displayed revision.
1661 * This will be null if not filled by setRevisionTimestamp().
1663 * @return string|null
1665 public function getRevisionTimestamp() {
1666 return $this->mRevisionTimestamp
;
1670 * Set the displayed file version
1672 * @param File|bool $file
1673 * @return mixed Previous value
1675 public function setFileVersion( $file ) {
1677 if ( $file instanceof File
&& $file->exists() ) {
1678 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1680 return wfSetVar( $this->mFileVersion
, $val, true );
1684 * Get the displayed file version
1686 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1688 public function getFileVersion() {
1689 return $this->mFileVersion
;
1693 * Get the templates used on this page
1695 * @return array (namespace => dbKey => revId)
1698 public function getTemplateIds() {
1699 return $this->mTemplateIds
;
1703 * Get the files used on this page
1705 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1708 public function getFileSearchOptions() {
1709 return $this->mImageTimeKeys
;
1713 * Convert wikitext to HTML and add it to the buffer
1714 * Default assumes that the current page title will be used.
1716 * @param string $text
1717 * @param bool $linestart Is this the start of a line?
1718 * @param bool $interface Is this text in the user interface language?
1719 * @throws MWException
1721 public function addWikiText( $text, $linestart = true, $interface = true ) {
1722 $title = $this->getTitle(); // Work around E_STRICT
1724 throw new MWException( 'Title is null' );
1726 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1730 * Add wikitext with a custom Title object
1732 * @param string $text Wikitext
1733 * @param Title &$title
1734 * @param bool $linestart Is this the start of a line?
1736 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1737 $this->addWikiTextTitle( $text, $title, $linestart );
1741 * Add wikitext with a custom Title object and tidy enabled.
1743 * @param string $text Wikitext
1744 * @param Title &$title
1745 * @param bool $linestart Is this the start of a line?
1747 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1748 $this->addWikiTextTitle( $text, $title, $linestart, true );
1752 * Add wikitext with tidy enabled
1754 * @param string $text Wikitext
1755 * @param bool $linestart Is this the start of a line?
1757 public function addWikiTextTidy( $text, $linestart = true ) {
1758 $title = $this->getTitle();
1759 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1763 * Add wikitext with a custom Title object
1765 * @param string $text Wikitext
1766 * @param Title $title
1767 * @param bool $linestart Is this the start of a line?
1768 * @param bool $tidy Whether to use tidy
1769 * @param bool $interface Whether it is an interface message
1770 * (for example disables conversion)
1772 public function addWikiTextTitle( $text, Title
$title, $linestart,
1773 $tidy = false, $interface = false
1777 $popts = $this->parserOptions();
1778 $oldTidy = $popts->setTidy( $tidy );
1779 $popts->setInterfaceMessage( (bool)$interface );
1781 $parserOutput = $wgParser->getFreshParser()->parse(
1782 $text, $title, $popts,
1783 $linestart, true, $this->mRevisionId
1786 $popts->setTidy( $oldTidy );
1788 $this->addParserOutput( $parserOutput, [
1789 'enableSectionEditLinks' => false,
1794 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1795 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1799 * @param ParserOutput $parserOutput
1801 public function addParserOutputMetadata( $parserOutput ) {
1802 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1803 $this->addCategoryLinks( $parserOutput->getCategories() );
1804 $this->setIndicators( $parserOutput->getIndicators() );
1805 $this->mNewSectionLink
= $parserOutput->getNewSection();
1806 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1808 if ( !$parserOutput->isCacheable() ) {
1809 $this->enableClientCache( false );
1811 $this->mNoGallery
= $parserOutput->getNoGallery();
1812 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1813 $this->addModules( $parserOutput->getModules() );
1814 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1815 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1816 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1817 $this->mPreventClickjacking
= $this->mPreventClickjacking
1818 ||
$parserOutput->preventClickjacking();
1820 // Template versioning...
1821 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1822 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1823 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1825 $this->mTemplateIds
[$ns] = $dbks;
1828 // File versioning...
1829 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1830 $this->mImageTimeKeys
[$dbk] = $data;
1833 // Hooks registered in the object
1834 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1835 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1836 list( $hookName, $data ) = $hookInfo;
1837 if ( isset( $parserOutputHooks[$hookName] ) ) {
1838 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1842 // Enable OOUI if requested via ParserOutput
1843 if ( $parserOutput->getEnableOOUI() ) {
1844 $this->enableOOUI();
1847 // Include parser limit report
1848 if ( !$this->limitReportJSData
) {
1849 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1852 // Link flags are ignored for now, but may in the future be
1853 // used to mark individual language links.
1855 // Avoid PHP 7.1 warning of passing $this by reference
1856 $outputPage = $this;
1857 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1858 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1860 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1861 // so that extensions may modify ParserOutput to toggle TOC.
1862 // This cannot be moved to addParserOutputText because that is not
1863 // called by EditPage for Preview.
1864 if ( $parserOutput->getTOCHTML() ) {
1865 $this->mEnableTOC
= true;
1870 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1871 * ParserOutput object, without any other metadata.
1874 * @param ParserOutput $parserOutput
1875 * @param array $poOptions Options to ParserOutput::getText()
1877 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1878 $this->addParserOutputText( $parserOutput, $poOptions );
1880 $this->addModules( $parserOutput->getModules() );
1881 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1882 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1884 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1888 * Add the HTML associated with a ParserOutput object, without any metadata.
1891 * @param ParserOutput $parserOutput
1892 * @param array $poOptions Options to ParserOutput::getText()
1894 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1895 $text = $parserOutput->getText( $poOptions );
1896 // Avoid PHP 7.1 warning of passing $this by reference
1897 $outputPage = $this;
1898 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1899 $this->addHTML( $text );
1903 * Add everything from a ParserOutput object.
1905 * @param ParserOutput $parserOutput
1906 * @param array $poOptions Options to ParserOutput::getText()
1908 function addParserOutput( $parserOutput, $poOptions = [] ) {
1909 $this->addParserOutputMetadata( $parserOutput );
1910 $this->addParserOutputText( $parserOutput, $poOptions );
1914 * Add the output of a QuickTemplate to the output buffer
1916 * @param QuickTemplate &$template
1918 public function addTemplate( &$template ) {
1919 $this->addHTML( $template->getHTML() );
1923 * Parse wikitext and return the HTML.
1925 * @param string $text
1926 * @param bool $linestart Is this the start of a line?
1927 * @param bool $interface Use interface language ($wgLang instead of
1928 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1929 * This also disables LanguageConverter.
1930 * @param Language $language Target language object, will override $interface
1931 * @throws MWException
1932 * @return string HTML
1934 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1937 if ( is_null( $this->getTitle() ) ) {
1938 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1941 $popts = $this->parserOptions();
1943 $popts->setInterfaceMessage( true );
1945 if ( $language !== null ) {
1946 $oldLang = $popts->setTargetLanguage( $language );
1949 $parserOutput = $wgParser->getFreshParser()->parse(
1950 $text, $this->getTitle(), $popts,
1951 $linestart, true, $this->mRevisionId
1955 $popts->setInterfaceMessage( false );
1957 if ( $language !== null ) {
1958 $popts->setTargetLanguage( $oldLang );
1961 return $parserOutput->getText( [
1962 'enableSectionEditLinks' => false,
1967 * Parse wikitext, strip paragraphs, and return the HTML.
1969 * @param string $text
1970 * @param bool $linestart Is this the start of a line?
1971 * @param bool $interface Use interface language ($wgLang instead of
1972 * $wgContLang) while parsing language sensitive magic
1973 * words like GRAMMAR and PLURAL
1974 * @return string HTML
1976 public function parseInline( $text, $linestart = true, $interface = false ) {
1977 $parsed = $this->parse( $text, $linestart, $interface );
1978 return Parser
::stripOuterParagraph( $parsed );
1982 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1984 * @param int $maxage Maximum cache time on the CDN, in seconds.
1986 public function setCdnMaxage( $maxage ) {
1987 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1991 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1993 * @param int $maxage Maximum cache time on the CDN, in seconds
1996 public function lowerCdnMaxage( $maxage ) {
1997 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1998 $this->setCdnMaxage( $this->mCdnMaxage
);
2002 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2004 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2005 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2006 * TTL is 90% of the age of the object, subject to the min and max.
2008 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2009 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2010 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2011 * @return int TTL in seconds
2014 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2015 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2016 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2018 if ( $mtime === null ||
$mtime === false ) {
2019 return $minTTL; // entity does not exist
2022 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2023 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2024 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2026 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2028 return $adaptiveTTL;
2032 * Use enableClientCache(false) to force it to send nocache headers
2034 * @param bool $state
2038 public function enableClientCache( $state ) {
2039 return wfSetVar( $this->mEnableClientCache
, $state );
2043 * Get the list of cookies that will influence on the cache
2047 function getCacheVaryCookies() {
2049 if ( $cookies === null ) {
2050 $config = $this->getConfig();
2051 $cookies = array_merge(
2052 SessionManager
::singleton()->getVaryCookies(),
2056 $config->get( 'CacheVaryCookies' )
2058 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2064 * Check if the request has a cache-varying cookie header
2065 * If it does, it's very important that we don't allow public caching
2069 function haveCacheVaryCookies() {
2070 $request = $this->getRequest();
2071 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2072 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2073 wfDebug( __METHOD__
. ": found $cookieName\n" );
2077 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2082 * Add an HTTP header that will influence on the cache
2084 * @param string $header Header name
2085 * @param string[]|null $option Options for the Key header. See
2086 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2087 * for the list of valid options.
2089 public function addVaryHeader( $header, array $option = null ) {
2090 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2091 $this->mVaryHeader
[$header] = [];
2093 if ( !is_array( $option ) ) {
2096 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2100 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2101 * such as Accept-Encoding or Cookie
2105 public function getVaryHeader() {
2106 // If we vary on cookies, let's make sure it's always included here too.
2107 if ( $this->getCacheVaryCookies() ) {
2108 $this->addVaryHeader( 'Cookie' );
2111 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2112 $this->addVaryHeader( $header, $options );
2114 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2118 * Add an HTTP Link: header
2120 * @param string $header Header value
2122 public function addLinkHeader( $header ) {
2123 $this->mLinkHeader
[] = $header;
2127 * Return a Link: header. Based on the values of $mLinkHeader.
2131 public function getLinkHeader() {
2132 if ( !$this->mLinkHeader
) {
2136 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2140 * Get a complete Key header
2144 public function getKeyHeader() {
2145 $cvCookies = $this->getCacheVaryCookies();
2147 $cookiesOption = [];
2148 foreach ( $cvCookies as $cookieName ) {
2149 $cookiesOption[] = 'param=' . $cookieName;
2151 $this->addVaryHeader( 'Cookie', $cookiesOption );
2153 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2154 $this->addVaryHeader( $header, $options );
2158 foreach ( $this->mVaryHeader
as $header => $option ) {
2159 $newheader = $header;
2160 if ( is_array( $option ) && count( $option ) > 0 ) {
2161 $newheader .= ';' . implode( ';', $option );
2163 $headers[] = $newheader;
2165 $key = 'Key: ' . implode( ',', $headers );
2171 * T23672: Add Accept-Language to Vary and Key headers
2172 * if there's no 'variant' parameter existed in GET.
2175 * /w/index.php?title=Main_page should always be served; but
2176 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2178 function addAcceptLanguage() {
2179 $title = $this->getTitle();
2180 if ( !$title instanceof Title
) {
2184 $lang = $title->getPageLanguage();
2185 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2186 $variants = $lang->getVariants();
2188 foreach ( $variants as $variant ) {
2189 if ( $variant === $lang->getCode() ) {
2192 $aloption[] = 'substr=' . $variant;
2194 // IE and some other browsers use BCP 47 standards in
2195 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2196 // We should handle these too.
2197 $variantBCP47 = LanguageCode
::bcp47( $variant );
2198 if ( $variantBCP47 !== $variant ) {
2199 $aloption[] = 'substr=' . $variantBCP47;
2203 $this->addVaryHeader( 'Accept-Language', $aloption );
2208 * Set a flag which will cause an X-Frame-Options header appropriate for
2209 * edit pages to be sent. The header value is controlled by
2210 * $wgEditPageFrameOptions.
2212 * This is the default for special pages. If you display a CSRF-protected
2213 * form on an ordinary view page, then you need to call this function.
2215 * @param bool $enable
2217 public function preventClickjacking( $enable = true ) {
2218 $this->mPreventClickjacking
= $enable;
2222 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2223 * This can be called from pages which do not contain any CSRF-protected
2226 public function allowClickjacking() {
2227 $this->mPreventClickjacking
= false;
2231 * Get the prevent-clickjacking flag
2236 public function getPreventClickjacking() {
2237 return $this->mPreventClickjacking
;
2241 * Get the X-Frame-Options header value (without the name part), or false
2242 * if there isn't one. This is used by Skin to determine whether to enable
2243 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2245 * @return string|false
2247 public function getFrameOptions() {
2248 $config = $this->getConfig();
2249 if ( $config->get( 'BreakFrames' ) ) {
2251 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2252 return $config->get( 'EditPageFrameOptions' );
2258 * Send cache control HTTP headers
2260 public function sendCacheControl() {
2261 $response = $this->getRequest()->response();
2262 $config = $this->getConfig();
2264 $this->addVaryHeader( 'Cookie' );
2265 $this->addAcceptLanguage();
2267 # don't serve compressed data to clients who can't handle it
2268 # maintain different caches for logged-in users and non-logged in ones
2269 $response->header( $this->getVaryHeader() );
2271 if ( $config->get( 'UseKeyHeader' ) ) {
2272 $response->header( $this->getKeyHeader() );
2275 if ( $this->mEnableClientCache
) {
2277 $config->get( 'UseSquid' ) &&
2278 !$response->hasCookies() &&
2279 !SessionManager
::getGlobalSession()->isPersistent() &&
2280 !$this->isPrintable() &&
2281 $this->mCdnMaxage
!= 0 &&
2282 !$this->haveCacheVaryCookies()
2284 if ( $config->get( 'UseESI' ) ) {
2285 # We'll purge the proxy cache explicitly, but require end user agents
2286 # to revalidate against the proxy on each visit.
2287 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2288 wfDebug( __METHOD__
.
2289 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2290 # start with a shorter timeout for initial testing
2291 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2293 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2294 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2296 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2298 # We'll purge the proxy cache for anons explicitly, but require end user agents
2299 # to revalidate against the proxy on each visit.
2300 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2301 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2302 wfDebug( __METHOD__
.
2303 ": local proxy caching; {$this->mLastModified} **", 'private' );
2304 # start with a shorter timeout for initial testing
2305 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2306 $response->header( "Cache-Control: " .
2307 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2310 # We do want clients to cache if they can, but they *must* check for updates
2311 # on revisiting the page.
2312 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2313 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2314 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2316 if ( $this->mLastModified
) {
2317 $response->header( "Last-Modified: {$this->mLastModified}" );
2320 wfDebug( __METHOD__
. ": no caching **", 'private' );
2322 # In general, the absence of a last modified header should be enough to prevent
2323 # the client from using its cache. We send a few other things just to make sure.
2324 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2325 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2326 $response->header( 'Pragma: no-cache' );
2331 * Transfer styles and JavaScript modules from skin.
2333 * @param Skin $sk to load modules for
2335 public function loadSkinModules( $sk ) {
2336 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2337 if ( $group === 'styles' ) {
2338 foreach ( $modules as $key => $moduleMembers ) {
2339 $this->addModuleStyles( $moduleMembers );
2342 $this->addModules( $modules );
2348 * Finally, all the text has been munged and accumulated into
2349 * the object, let's actually output it:
2351 * @param bool $return Set to true to get the result as a string rather than sending it
2352 * @return string|null
2354 * @throws FatalError
2355 * @throws MWException
2357 public function output( $return = false ) {
2360 if ( $this->mDoNothing
) {
2361 return $return ?
'' : null;
2364 $response = $this->getRequest()->response();
2365 $config = $this->getConfig();
2367 if ( $this->mRedirect
!= '' ) {
2368 # Standards require redirect URLs to be absolute
2369 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2371 $redirect = $this->mRedirect
;
2372 $code = $this->mRedirectCode
;
2374 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2375 if ( $code == '301' ||
$code == '303' ) {
2376 if ( !$config->get( 'DebugRedirects' ) ) {
2377 $response->statusHeader( $code );
2379 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2381 if ( $config->get( 'VaryOnXFP' ) ) {
2382 $this->addVaryHeader( 'X-Forwarded-Proto' );
2384 $this->sendCacheControl();
2386 $response->header( "Content-Type: text/html; charset=utf-8" );
2387 if ( $config->get( 'DebugRedirects' ) ) {
2388 $url = htmlspecialchars( $redirect );
2389 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2390 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2391 print "</body>\n</html>\n";
2393 $response->header( 'Location: ' . $redirect );
2397 return $return ?
'' : null;
2398 } elseif ( $this->mStatusCode
) {
2399 $response->statusHeader( $this->mStatusCode
);
2402 # Buffer output; final headers may depend on later processing
2405 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2406 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2408 if ( !$this->mArticleBodyOnly
) {
2409 $sk = $this->getSkin();
2411 if ( $sk->shouldPreloadLogo() ) {
2412 $this->addLogoPreloadLinkHeaders();
2416 $linkHeader = $this->getLinkHeader();
2417 if ( $linkHeader ) {
2418 $response->header( $linkHeader );
2421 // Prevent framing, if requested
2422 $frameOptions = $this->getFrameOptions();
2423 if ( $frameOptions ) {
2424 $response->header( "X-Frame-Options: $frameOptions" );
2427 ContentSecurityPolicy
::sendHeaders( $this );
2429 if ( $this->mArticleBodyOnly
) {
2430 echo $this->mBodytext
;
2432 // Enable safe mode if requested (T152169)
2433 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2434 $this->disallowUserJs();
2437 $sk = $this->getSkin();
2438 $this->loadSkinModules( $sk );
2440 MWDebug
::addModules( $this );
2442 // Avoid PHP 7.1 warning of passing $this by reference
2443 $outputPage = $this;
2444 // Hook that allows last minute changes to the output page, e.g.
2445 // adding of CSS or Javascript by extensions.
2446 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2450 } catch ( Exception
$e ) {
2451 ob_end_clean(); // bug T129657
2457 // This hook allows last minute changes to final overall output by modifying output buffer
2458 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2459 } catch ( Exception
$e ) {
2460 ob_end_clean(); // bug T129657
2464 $this->sendCacheControl();
2467 return ob_get_clean();
2475 * Prepare this object to display an error page; disable caching and
2476 * indexing, clear the current text and redirect, set the page's title
2477 * and optionally an custom HTML title (content of the "<title>" tag).
2479 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2480 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2481 * optional, if not passed the "<title>" attribute will be
2482 * based on $pageTitle
2484 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2485 $this->setPageTitle( $pageTitle );
2486 if ( $htmlTitle !== false ) {
2487 $this->setHTMLTitle( $htmlTitle );
2489 $this->setRobotPolicy( 'noindex,nofollow' );
2490 $this->setArticleRelated( false );
2491 $this->enableClientCache( false );
2492 $this->mRedirect
= '';
2493 $this->clearSubtitle();
2498 * Output a standard error page
2500 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2501 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2502 * showErrorPage( 'titlemsg', $messageObject );
2503 * showErrorPage( $titleMessageObject, $messageObject );
2505 * @param string|Message $title Message key (string) for page title, or a Message object
2506 * @param string|Message $msg Message key (string) for page text, or a Message object
2507 * @param array $params Message parameters; ignored if $msg is a Message object
2509 public function showErrorPage( $title, $msg, $params = [] ) {
2510 if ( !$title instanceof Message
) {
2511 $title = $this->msg( $title );
2514 $this->prepareErrorPage( $title );
2516 if ( $msg instanceof Message
) {
2517 if ( $params !== [] ) {
2518 trigger_error( 'Argument ignored: $params. The message parameters argument '
2519 . 'is discarded when the $msg argument is a Message object instead of '
2520 . 'a string.', E_USER_NOTICE
);
2522 $this->addHTML( $msg->parseAsBlock() );
2524 $this->addWikiMsgArray( $msg, $params );
2527 $this->returnToMain();
2531 * Output a standard permission error page
2533 * @param array $errors Error message keys or [key, param...] arrays
2534 * @param string $action Action that was denied or null if unknown
2536 public function showPermissionsErrorPage( array $errors, $action = null ) {
2537 foreach ( $errors as $key => $error ) {
2538 $errors[$key] = (array)$error;
2541 // For some action (read, edit, create and upload), display a "login to do this action"
2542 // error if all of the following conditions are met:
2543 // 1. the user is not logged in
2544 // 2. the only error is insufficient permissions (i.e. no block or something else)
2545 // 3. the error can be avoided simply by logging in
2546 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2547 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2548 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2549 && ( User
::groupHasPermission( 'user', $action )
2550 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2552 $displayReturnto = null;
2554 # Due to T34276, if a user does not have read permissions,
2555 # $this->getTitle() will just give Special:Badtitle, which is
2556 # not especially useful as a returnto parameter. Use the title
2557 # from the request instead, if there was one.
2558 $request = $this->getRequest();
2559 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2560 if ( $action == 'edit' ) {
2561 $msg = 'whitelistedittext';
2562 $displayReturnto = $returnto;
2563 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2564 $msg = 'nocreatetext';
2565 } elseif ( $action == 'upload' ) {
2566 $msg = 'uploadnologintext';
2568 $msg = 'loginreqpagetext';
2569 $displayReturnto = Title
::newMainPage();
2575 $query['returnto'] = $returnto->getPrefixedText();
2577 if ( !$request->wasPosted() ) {
2578 $returntoquery = $request->getValues();
2579 unset( $returntoquery['title'] );
2580 unset( $returntoquery['returnto'] );
2581 unset( $returntoquery['returntoquery'] );
2582 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2585 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2586 $loginLink = $linkRenderer->makeKnownLink(
2587 SpecialPage
::getTitleFor( 'Userlogin' ),
2588 $this->msg( 'loginreqlink' )->text(),
2593 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2594 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2596 # Don't return to a page the user can't read otherwise
2597 # we'll end up in a pointless loop
2598 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2599 $this->returnToMain( null, $displayReturnto );
2602 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2603 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2608 * Display an error page indicating that a given version of MediaWiki is
2609 * required to use it
2611 * @param mixed $version The version of MediaWiki needed to use the page
2613 public function versionRequired( $version ) {
2614 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2616 $this->addWikiMsg( 'versionrequiredtext', $version );
2617 $this->returnToMain();
2621 * Format a list of error messages
2623 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2624 * @param string $action Action that was denied or null if unknown
2625 * @return string The wikitext error-messages, formatted into a list.
2627 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2628 if ( $action == null ) {
2629 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2631 $action_desc = $this->msg( "action-$action" )->plain();
2633 'permissionserrorstext-withaction',
2636 )->plain() . "\n\n";
2639 if ( count( $errors ) > 1 ) {
2640 $text .= '<ul class="permissions-errors">' . "\n";
2642 foreach ( $errors as $error ) {
2644 $text .= $this->msg( ...$error )->plain();
2649 $text .= "<div class=\"permissions-errors\">\n" .
2650 $this->msg( ...reset( $errors ) )->plain() .
2658 * Show a warning about replica DB lag
2660 * If the lag is higher than $wgSlaveLagCritical seconds,
2661 * then the warning is a bit more obvious. If the lag is
2662 * lower than $wgSlaveLagWarning, then no warning is shown.
2664 * @param int $lag Slave lag
2666 public function showLagWarning( $lag ) {
2667 $config = $this->getConfig();
2668 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2669 $lag = floor( $lag ); // floor to avoid nano seconds to display
2670 $message = $lag < $config->get( 'SlaveLagCritical' )
2673 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2674 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2678 public function showFatalError( $message ) {
2679 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2681 $this->addHTML( $message );
2684 public function showUnexpectedValueError( $name, $val ) {
2685 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2688 public function showFileCopyError( $old, $new ) {
2689 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2692 public function showFileRenameError( $old, $new ) {
2693 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2696 public function showFileDeleteError( $name ) {
2697 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2700 public function showFileNotFoundError( $name ) {
2701 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2705 * Add a "return to" link pointing to a specified title
2707 * @param Title $title Title to link
2708 * @param array $query Query string parameters
2709 * @param string $text Text of the link (input is not escaped)
2710 * @param array $options Options array to pass to Linker
2712 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2713 $linkRenderer = MediaWikiServices
::getInstance()
2714 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2715 $link = $this->msg( 'returnto' )->rawParams(
2716 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2717 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2721 * Add a "return to" link pointing to a specified title,
2722 * or the title indicated in the request, or else the main page
2724 * @param mixed $unused
2725 * @param Title|string $returnto Title or String to return to
2726 * @param string $returntoquery Query string for the return to link
2728 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2729 if ( $returnto == null ) {
2730 $returnto = $this->getRequest()->getText( 'returnto' );
2733 if ( $returntoquery == null ) {
2734 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2737 if ( $returnto === '' ) {
2738 $returnto = Title
::newMainPage();
2741 if ( is_object( $returnto ) ) {
2742 $titleObj = $returnto;
2744 $titleObj = Title
::newFromText( $returnto );
2746 // We don't want people to return to external interwiki. That
2747 // might potentially be used as part of a phishing scheme
2748 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2749 $titleObj = Title
::newMainPage();
2752 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2755 private function getRlClientContext() {
2756 if ( !$this->rlClientContext
) {
2757 $query = ResourceLoader
::makeLoaderQuery(
2758 [], // modules; not relevant
2759 $this->getLanguage()->getCode(),
2760 $this->getSkin()->getSkinName(),
2761 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2762 null, // version; not relevant
2763 ResourceLoader
::inDebugMode(),
2764 null, // only; not relevant
2765 $this->isPrintable(),
2766 $this->getRequest()->getBool( 'handheld' )
2768 $this->rlClientContext
= new ResourceLoaderContext(
2769 $this->getResourceLoader(),
2770 new FauxRequest( $query )
2772 if ( $this->contentOverrideCallbacks
) {
2773 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2774 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2775 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2776 $content = call_user_func( $callback, $title );
2777 if ( $content !== null ) {
2785 return $this->rlClientContext
;
2789 * Call this to freeze the module queue and JS config and create a formatter.
2791 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2792 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2793 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2794 * the module filters retroactively. Skins and extension hooks may also add modules until very
2795 * late in the request lifecycle.
2797 * @return ResourceLoaderClientHtml
2799 public function getRlClient() {
2800 if ( !$this->rlClient
) {
2801 $context = $this->getRlClientContext();
2802 $rl = $this->getResourceLoader();
2803 $this->addModules( [
2808 $this->addModuleStyles( [
2813 $this->getSkin()->setupSkinUserCss( $this );
2815 // Prepare exempt modules for buildExemptModules()
2816 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2818 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2820 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2821 // Separate user-specific batch for improved cache-hit ratio.
2822 $userBatch = [ 'user.styles', 'user' ];
2823 $siteBatch = array_diff( $moduleStyles, $userBatch );
2824 $dbr = wfGetDB( DB_REPLICA
);
2825 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2826 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2828 // Filter out modules handled by buildExemptModules()
2829 $moduleStyles = array_filter( $moduleStyles,
2830 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2831 $module = $rl->getModule( $name );
2833 $group = $module->getGroup();
2834 if ( isset( $exemptGroups[$group] ) ) {
2835 $exemptStates[$name] = 'ready';
2836 if ( !$module->isKnownEmpty( $context ) ) {
2837 // E.g. Don't output empty <styles>
2838 $exemptGroups[$group][] = $name;
2846 $this->rlExemptStyleModules
= $exemptGroups;
2848 $rlClient = new ResourceLoaderClientHtml( $context, [
2849 'target' => $this->getTarget(),
2850 'nonce' => $this->getCSPNonce(),
2851 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2852 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2853 // modules enqueud for loading on this page is filtered to just those.
2854 // However, to make sure we also apply the restriction to dynamic dependencies and
2855 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2856 // StartupModule so that the client-side registry will not contain any restricted
2857 // modules either. (T152169, T185303)
2858 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2859 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2862 $rlClient->setConfig( $this->getJSVars() );
2863 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2864 $rlClient->setModuleStyles( $moduleStyles );
2865 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2866 $rlClient->setExemptStates( $exemptStates );
2867 $this->rlClient
= $rlClient;
2869 return $this->rlClient
;
2873 * @param Skin $sk The given Skin
2874 * @param bool $includeStyle Unused
2875 * @return string The doctype, opening "<html>", and head element.
2877 public function headElement( Skin
$sk, $includeStyle = true ) {
2880 $userdir = $this->getLanguage()->getDir();
2881 $sitedir = $wgContLang->getDir();
2884 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2885 $this->getRlClient()->getDocumentAttributes(),
2886 $sk->getHtmlElementAttributes()
2888 $pieces[] = Html
::openElement( 'head' );
2890 if ( $this->getHTMLTitle() == '' ) {
2891 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2894 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2895 // Add <meta charset="UTF-8">
2896 // This should be before <title> since it defines the charset used by
2897 // text including the text inside <title>.
2898 // The spec recommends defining XHTML5's charset using the XML declaration
2900 // Our XML declaration is output by Html::htmlHeader.
2901 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2902 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2903 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2906 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2907 $pieces[] = $this->getRlClient()->getHeadHtml();
2908 $pieces[] = $this->buildExemptModules();
2909 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2910 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2912 // Use an IE conditional comment to serve the script only to old IE
2913 $pieces[] = '<!--[if lt IE 9]>' .
2914 ResourceLoaderClientHtml
::makeLoad(
2915 ResourceLoaderContext
::newDummyContext(),
2917 ResourceLoaderModule
::TYPE_SCRIPTS
,
2919 $this->getCSPNonce()
2923 $pieces[] = Html
::closeElement( 'head' );
2925 $bodyClasses = $this->mAdditionalBodyClasses
;
2926 $bodyClasses[] = 'mediawiki';
2928 # Classes for LTR/RTL directionality support
2929 $bodyClasses[] = $userdir;
2930 $bodyClasses[] = "sitedir-$sitedir";
2932 $underline = $this->getUser()->getOption( 'underline' );
2933 if ( $underline < 2 ) {
2934 // The following classes can be used here:
2935 // * mw-underline-always
2936 // * mw-underline-never
2937 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2940 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2941 # A <body> class is probably not the best way to do this . . .
2942 $bodyClasses[] = 'capitalize-all-nouns';
2945 // Parser feature migration class
2946 // The idea is that this will eventually be removed, after the wikitext
2947 // which requires it is cleaned up.
2948 $bodyClasses[] = 'mw-hide-empty-elt';
2950 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2951 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2953 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2956 // While the implode() is not strictly needed, it's used for backwards compatibility
2957 // (this used to be built as a string and hooks likely still expect that).
2958 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2960 // Allow skins and extensions to add body attributes they need
2961 $sk->addToBodyAttributes( $this, $bodyAttrs );
2962 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2964 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2966 return self
::combineWrappedStrings( $pieces );
2970 * Get a ResourceLoader object associated with this OutputPage
2972 * @return ResourceLoader
2974 public function getResourceLoader() {
2975 if ( is_null( $this->mResourceLoader
) ) {
2976 $this->mResourceLoader
= new ResourceLoader(
2978 LoggerFactory
::getInstance( 'resourceloader' )
2981 return $this->mResourceLoader
;
2985 * Explicily load or embed modules on a page.
2987 * @param array|string $modules One or more module names
2988 * @param string $only ResourceLoaderModule TYPE_ class constant
2989 * @param array $extraQuery [optional] Array with extra query parameters for the request
2990 * @return string|WrappedStringList HTML
2992 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2993 // Apply 'target' and 'origin' filters
2994 $modules = $this->filterModules( (array)$modules, null, $only );
2996 return ResourceLoaderClientHtml
::makeLoad(
2997 $this->getRlClientContext(),
3001 $this->getCSPNonce()
3006 * Combine WrappedString chunks and filter out empty ones
3008 * @param array $chunks
3009 * @return string|WrappedStringList HTML
3011 protected static function combineWrappedStrings( array $chunks ) {
3012 // Filter out empty values
3013 $chunks = array_filter( $chunks, 'strlen' );
3014 return WrappedString
::join( "\n", $chunks );
3018 * JS stuff to put at the bottom of the `<body>`.
3019 * These are legacy scripts ($this->mScripts), and user JS.
3021 * @return string|WrappedStringList HTML
3023 public function getBottomScripts() {
3025 $chunks[] = $this->getRlClient()->getBodyHtml();
3027 // Legacy non-ResourceLoader scripts
3028 $chunks[] = $this->mScripts
;
3030 if ( $this->limitReportJSData
) {
3031 $chunks[] = ResourceLoader
::makeInlineScript(
3032 ResourceLoader
::makeConfigSetScript(
3033 [ 'wgPageParseReport' => $this->limitReportJSData
]
3035 $this->getCSPNonce()
3039 return self
::combineWrappedStrings( $chunks );
3043 * Get the javascript config vars to include on this page
3045 * @return array Array of javascript config vars
3048 public function getJsConfigVars() {
3049 return $this->mJsConfigVars
;
3053 * Add one or more variables to be set in mw.config in JavaScript
3055 * @param string|array $keys Key or array of key/value pairs
3056 * @param mixed $value [optional] Value of the configuration variable
3058 public function addJsConfigVars( $keys, $value = null ) {
3059 if ( is_array( $keys ) ) {
3060 foreach ( $keys as $key => $value ) {
3061 $this->mJsConfigVars
[$key] = $value;
3066 $this->mJsConfigVars
[$keys] = $value;
3070 * Get an array containing the variables to be set in mw.config in JavaScript.
3072 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3073 * - in other words, page-independent/site-wide variables (without state).
3074 * You will only be adding bloat to the html page and causing page caches to
3075 * have to be purged on configuration changes.
3078 public function getJSVars() {
3083 $canonicalSpecialPageName = false; # T23115
3085 $title = $this->getTitle();
3086 $ns = $title->getNamespace();
3087 $canonicalNamespace = MWNamespace
::exists( $ns )
3088 ? MWNamespace
::getCanonicalName( $ns )
3089 : $title->getNsText();
3091 $sk = $this->getSkin();
3092 // Get the relevant title so that AJAX features can use the correct page name
3093 // when making API requests from certain special pages (T36972).
3094 $relevantTitle = $sk->getRelevantTitle();
3095 $relevantUser = $sk->getRelevantUser();
3097 if ( $ns == NS_SPECIAL
) {
3098 list( $canonicalSpecialPageName, /*...*/ ) =
3099 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3100 } elseif ( $this->canUseWikiPage() ) {
3101 $wikiPage = $this->getWikiPage();
3102 $curRevisionId = $wikiPage->getLatest();
3103 $articleId = $wikiPage->getId();
3106 $lang = $title->getPageViewLanguage();
3108 // Pre-process information
3109 $separatorTransTable = $lang->separatorTransformTable();
3110 $separatorTransTable = $separatorTransTable ?
: [];
3111 $compactSeparatorTransTable = [
3112 implode( "\t", array_keys( $separatorTransTable ) ),
3113 implode( "\t", $separatorTransTable ),
3115 $digitTransTable = $lang->digitTransformTable();
3116 $digitTransTable = $digitTransTable ?
: [];
3117 $compactDigitTransTable = [
3118 implode( "\t", array_keys( $digitTransTable ) ),
3119 implode( "\t", $digitTransTable ),
3122 $user = $this->getUser();
3125 'wgCanonicalNamespace' => $canonicalNamespace,
3126 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3127 'wgNamespaceNumber' => $title->getNamespace(),
3128 'wgPageName' => $title->getPrefixedDBkey(),
3129 'wgTitle' => $title->getText(),
3130 'wgCurRevisionId' => $curRevisionId,
3131 'wgRevisionId' => (int)$this->getRevisionId(),
3132 'wgArticleId' => $articleId,
3133 'wgIsArticle' => $this->isArticle(),
3134 'wgIsRedirect' => $title->isRedirect(),
3135 'wgAction' => Action
::getActionName( $this->getContext() ),
3136 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3137 'wgUserGroups' => $user->getEffectiveGroups(),
3138 'wgCategories' => $this->getCategories(),
3139 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3140 'wgPageContentLanguage' => $lang->getCode(),
3141 'wgPageContentModel' => $title->getContentModel(),
3142 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3143 'wgDigitTransformTable' => $compactDigitTransTable,
3144 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3145 'wgMonthNames' => $lang->getMonthNamesArray(),
3146 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3147 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3148 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3149 'wgRequestId' => WebRequest
::getRequestId(),
3152 if ( $user->isLoggedIn() ) {
3153 $vars['wgUserId'] = $user->getId();
3154 $vars['wgUserEditCount'] = $user->getEditCount();
3155 $userReg = $user->getRegistration();
3156 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3157 // Get the revision ID of the oldest new message on the user's talk
3158 // page. This can be used for constructing new message alerts on
3160 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3163 if ( $wgContLang->hasVariants() ) {
3164 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3166 // Same test as SkinTemplate
3167 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3168 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3170 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3171 && $relevantTitle->quickUserCan( 'edit', $user )
3172 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3174 foreach ( $title->getRestrictionTypes() as $type ) {
3175 // Following keys are set in $vars:
3176 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3177 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3180 if ( $title->isMainPage() ) {
3181 $vars['wgIsMainPage'] = true;
3184 if ( $this->mRedirectedFrom
) {
3185 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3188 if ( $relevantUser ) {
3189 $vars['wgRelevantUserName'] = $relevantUser->getName();
3192 // Allow extensions to add their custom variables to the mw.config map.
3193 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3194 // page-dependant but site-wide (without state).
3195 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3196 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3198 // Merge in variables from addJsConfigVars last
3199 return array_merge( $vars, $this->getJsConfigVars() );
3203 * To make it harder for someone to slip a user a fake
3204 * JavaScript or CSS preview, a random token
3205 * is associated with the login session. If it's not
3206 * passed back with the preview request, we won't render
3211 public function userCanPreview() {
3212 $request = $this->getRequest();
3214 $request->getVal( 'action' ) !== 'submit' ||
3215 !$request->wasPosted()
3220 $user = $this->getUser();
3222 if ( !$user->isLoggedIn() ) {
3223 // Anons have predictable edit tokens
3226 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3230 $title = $this->getTitle();
3231 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3232 if ( count( $errors ) !== 0 ) {
3240 * @return array Array in format "link name or number => 'link html'".
3242 public function getHeadLinksArray() {
3246 $config = $this->getConfig();
3248 $canonicalUrl = $this->mCanonicalUrl
;
3250 $tags['meta-generator'] = Html
::element( 'meta', [
3251 'name' => 'generator',
3252 'content' => "MediaWiki $wgVersion",
3255 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3256 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3257 // fallbacks should come before the primary value so we need to reverse the array.
3258 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3259 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3260 'name' => 'referrer',
3261 'content' => $policy,
3266 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3267 if ( $p !== 'index,follow' ) {
3268 // http://www.robotstxt.org/wc/meta-user.html
3269 // Only show if it's different from the default robots policy
3270 $tags['meta-robots'] = Html
::element( 'meta', [
3276 foreach ( $this->mMetatags
as $tag ) {
3277 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3279 $tag[0] = substr( $tag[0], 5 );
3280 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3285 $tagName = "meta-{$tag[0]}";
3286 if ( isset( $tags[$tagName] ) ) {
3287 $tagName .= $tag[1];
3289 $tags[$tagName] = Html
::element( 'meta',
3292 'content' => $tag[1]
3297 foreach ( $this->mLinktags
as $tag ) {
3298 $tags[] = Html
::element( 'link', $tag );
3301 # Universal edit button
3302 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3303 $user = $this->getUser();
3304 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3305 && ( $this->getTitle()->exists() ||
3306 $this->getTitle()->quickUserCan( 'create', $user ) )
3308 // Original UniversalEditButton
3309 $msg = $this->msg( 'edit' )->text();
3310 $tags['universal-edit-button'] = Html
::element( 'link', [
3311 'rel' => 'alternate',
3312 'type' => 'application/x-wiki',
3314 'href' => $this->getTitle()->getEditURL(),
3316 // Alternate edit link
3317 $tags['alternative-edit'] = Html
::element( 'link', [
3320 'href' => $this->getTitle()->getEditURL(),
3325 # Generally the order of the favicon and apple-touch-icon links
3326 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3327 # uses whichever one appears later in the HTML source. Make sure
3328 # apple-touch-icon is specified first to avoid this.
3329 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3330 $tags['apple-touch-icon'] = Html
::element( 'link', [
3331 'rel' => 'apple-touch-icon',
3332 'href' => $config->get( 'AppleTouchIcon' )
3336 if ( $config->get( 'Favicon' ) !== false ) {
3337 $tags['favicon'] = Html
::element( 'link', [
3338 'rel' => 'shortcut icon',
3339 'href' => $config->get( 'Favicon' )
3343 # OpenSearch description link
3344 $tags['opensearch'] = Html
::element( 'link', [
3346 'type' => 'application/opensearchdescription+xml',
3347 'href' => wfScript( 'opensearch_desc' ),
3348 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3351 # Real Simple Discovery link, provides auto-discovery information
3352 # for the MediaWiki API (and potentially additional custom API
3353 # support such as WordPress or Twitter-compatible APIs for a
3354 # blogging extension, etc)
3355 $tags['rsd'] = Html
::element( 'link', [
3357 'type' => 'application/rsd+xml',
3358 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3359 // Whether RSD accepts relative or protocol-relative URLs is completely
3360 // undocumented, though.
3361 'href' => wfExpandUrl( wfAppendQuery(
3363 [ 'action' => 'rsd' ] ),
3369 if ( !$config->get( 'DisableLangConversion' ) ) {
3370 $lang = $this->getTitle()->getPageLanguage();
3371 if ( $lang->hasVariants() ) {
3372 $variants = $lang->getVariants();
3373 foreach ( $variants as $variant ) {
3374 $tags["variant-$variant"] = Html
::element( 'link', [
3375 'rel' => 'alternate',
3376 'hreflang' => LanguageCode
::bcp47( $variant ),
3377 'href' => $this->getTitle()->getLocalURL(
3378 [ 'variant' => $variant ] )
3382 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3383 $tags["variant-x-default"] = Html
::element( 'link', [
3384 'rel' => 'alternate',
3385 'hreflang' => 'x-default',
3386 'href' => $this->getTitle()->getLocalURL() ] );
3391 if ( $this->copyrightUrl
!== null ) {
3392 $copyright = $this->copyrightUrl
;
3395 if ( $config->get( 'RightsPage' ) ) {
3396 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3399 $copyright = $copy->getLocalURL();
3403 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3404 $copyright = $config->get( 'RightsUrl' );
3409 $tags['copyright'] = Html
::element( 'link', [
3411 'href' => $copyright ]
3416 if ( $config->get( 'Feed' ) ) {
3419 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3420 # Use the page name for the title. In principle, this could
3421 # lead to issues with having the same name for different feeds
3422 # corresponding to the same page, but we can't avoid that at
3425 $feedLinks[] = $this->feedLink(
3428 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3430 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3435 # Recent changes feed should appear on every page (except recentchanges,
3436 # that would be redundant). Put it after the per-page feed to avoid
3437 # changing existing behavior. It's still available, probably via a
3438 # menu in your browser. Some sites might have a different feed they'd
3439 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3440 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3441 # If so, use it instead.
3442 $sitename = $config->get( 'Sitename' );
3443 if ( $config->get( 'OverrideSiteFeed' ) ) {
3444 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3445 // Note, this->feedLink escapes the url.
3446 $feedLinks[] = $this->feedLink(
3449 $this->msg( "site-{$type}-feed", $sitename )->text()
3452 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3453 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3454 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3455 $feedLinks[] = $this->feedLink(
3457 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3458 # For grep: 'site-rss-feed', 'site-atom-feed'
3459 $this->msg( "site-{$format}-feed", $sitename )->text()
3464 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3465 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3466 # use OutputPage::addFeedLink() instead.
3467 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3469 $tags +
= $feedLinks;
3473 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3474 if ( $canonicalUrl !== false ) {
3475 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3477 if ( $this->isArticleRelated() ) {
3478 // This affects all requests where "setArticleRelated" is true. This is
3479 // typically all requests that show content (query title, curid, oldid, diff),
3480 // and all wikipage actions (edit, delete, purge, info, history etc.).
3481 // It does not apply to File pages and Special pages.
3482 // 'history' and 'info' actions address page metadata rather than the page
3483 // content itself, so they may not be canonicalized to the view page url.
3484 // TODO: this ought to be better encapsulated in the Action class.
3485 $action = Action
::getActionName( $this->getContext() );
3486 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3487 $query = "action={$action}";
3491 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3493 $reqUrl = $this->getRequest()->getRequestURL();
3494 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3498 if ( $canonicalUrl !== false ) {
3499 $tags[] = Html
::element( 'link', [
3500 'rel' => 'canonical',
3501 'href' => $canonicalUrl
3509 * Generate a "<link rel/>" for a feed.
3511 * @param string $type Feed type
3512 * @param string $url URL to the feed
3513 * @param string $text Value of the "title" attribute
3514 * @return string HTML fragment
3516 private function feedLink( $type, $url, $text ) {
3517 return Html
::element( 'link', [
3518 'rel' => 'alternate',
3519 'type' => "application/$type+xml",
3526 * Add a local or specified stylesheet, with the given media options.
3527 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3529 * @param string $style URL to the file
3530 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3531 * @param string $condition For IE conditional comments, specifying an IE version
3532 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3534 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3537 $options['media'] = $media;
3540 $options['condition'] = $condition;
3543 $options['dir'] = $dir;
3545 $this->styles
[$style] = $options;
3549 * Adds inline CSS styles
3550 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3552 * @param mixed $style_css Inline CSS
3553 * @param string $flip Set to 'flip' to flip the CSS if needed
3555 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3556 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3557 # If wanted, and the interface is right-to-left, flip the CSS
3558 $style_css = CSSJanus
::transform( $style_css, true, false );
3560 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3564 * Build exempt modules and legacy non-ResourceLoader styles.
3566 * @return string|WrappedStringList HTML
3568 protected function buildExemptModules() {
3570 // Things that go after the ResourceLoaderDynamicStyles marker
3573 // We want site, private and user styles to override dynamically added styles from
3574 // general modules, but we want dynamically added styles to override statically added
3575 // style modules. So the order has to be:
3576 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3577 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3578 // - ResourceLoaderDynamicStyles marker
3579 // - site/private/user styles
3581 // Add legacy styles added through addStyle()/addInlineStyle() here
3582 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3584 $chunks[] = Html
::element(
3586 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3589 $separateReq = [ 'site.styles', 'user.styles' ];
3590 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3591 // Combinable modules
3592 $chunks[] = $this->makeResourceLoaderLink(
3593 array_diff( $moduleNames, $separateReq ),
3594 ResourceLoaderModule
::TYPE_STYLES
3597 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3598 // These require their own dedicated request in order to support "@import"
3599 // syntax, which is incompatible with concatenation. (T147667, T37562)
3600 $chunks[] = $this->makeResourceLoaderLink( $name,
3601 ResourceLoaderModule
::TYPE_STYLES
3606 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3612 public function buildCssLinksArray() {
3615 foreach ( $this->styles
as $file => $options ) {
3616 $link = $this->styleLink( $file, $options );
3618 $links[$file] = $link;
3625 * Generate \<link\> tags for stylesheets
3627 * @param string $style URL to the file
3628 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3629 * @return string HTML fragment
3631 protected function styleLink( $style, array $options ) {
3632 if ( isset( $options['dir'] ) ) {
3633 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3638 if ( isset( $options['media'] ) ) {
3639 $media = self
::transformCssMedia( $options['media'] );
3640 if ( is_null( $media ) ) {
3647 if ( substr( $style, 0, 1 ) == '/' ||
3648 substr( $style, 0, 5 ) == 'http:' ||
3649 substr( $style, 0, 6 ) == 'https:' ) {
3652 $config = $this->getConfig();
3653 // Append file hash as query parameter
3654 $url = self
::transformResourcePath(
3656 $config->get( 'StylePath' ) . '/' . $style
3660 $link = Html
::linkedStyle( $url, $media );
3662 if ( isset( $options['condition'] ) ) {
3663 $condition = htmlspecialchars( $options['condition'] );
3664 $link = "<!--[if $condition]>$link<![endif]-->";
3670 * Transform path to web-accessible static resource.
3672 * This is used to add a validation hash as query string.
3673 * This aids various behaviors:
3675 * - Put long Cache-Control max-age headers on responses for improved
3676 * cache performance.
3677 * - Get the correct version of a file as expected by the current page.
3678 * - Instantly get the updated version of a file after deployment.
3680 * Avoid using this for urls included in HTML as otherwise clients may get different
3681 * versions of a resource when navigating the site depending on when the page was cached.
3682 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3683 * an external stylesheet).
3686 * @param Config $config
3687 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3688 * @return string URL
3690 public static function transformResourcePath( Config
$config, $path ) {
3694 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3695 if ( $remotePathPrefix === '' ) {
3696 // The configured base path is required to be empty string for
3697 // wikis in the domain root
3700 $remotePath = $remotePathPrefix;
3702 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3703 // - Path is outside wgResourceBasePath, ignore.
3704 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3707 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3708 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3709 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3710 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3711 $uploadPath = $config->get( 'UploadPath' );
3712 if ( strpos( $path, $uploadPath ) === 0 ) {
3713 $localDir = $config->get( 'UploadDirectory' );
3714 $remotePathPrefix = $remotePath = $uploadPath;
3717 $path = RelPath
::getRelativePath( $path, $remotePath );
3718 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3722 * Utility method for transformResourceFilePath().
3724 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3727 * @param string $remotePathPrefix URL path prefix that points to $localPath
3728 * @param string $localPath File directory exposed at $remotePath
3729 * @param string $file Path to target file relative to $localPath
3730 * @return string URL
3732 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3733 $hash = md5_file( "$localPath/$file" );
3734 if ( $hash === false ) {
3735 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3738 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3742 * Transform "media" attribute based on request parameters
3744 * @param string $media Current value of the "media" attribute
3745 * @return string Modified value of the "media" attribute, or null to skip
3748 public static function transformCssMedia( $media ) {
3751 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3752 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3754 // Switch in on-screen display for media testing
3756 'printable' => 'print',
3757 'handheld' => 'handheld',
3759 foreach ( $switches as $switch => $targetMedia ) {
3760 if ( $wgRequest->getBool( $switch ) ) {
3761 if ( $media == $targetMedia ) {
3763 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3764 /* This regex will not attempt to understand a comma-separated media_query_list
3766 * Example supported values for $media:
3767 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3768 * Example NOT supported value for $media:
3769 * '3d-glasses, screen, print and resolution > 90dpi'
3771 * If it's a print request, we never want any kind of screen stylesheets
3772 * If it's a handheld request (currently the only other choice with a switch),
3773 * we don't want simple 'screen' but we might want screen queries that
3774 * have a max-width or something, so we'll pass all others on and let the
3775 * client do the query.
3777 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3788 * Add a wikitext-formatted message to the output.
3789 * This is equivalent to:
3791 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3793 public function addWikiMsg( /*...*/ ) {
3794 $args = func_get_args();
3795 $name = array_shift( $args );
3796 $this->addWikiMsgArray( $name, $args );
3800 * Add a wikitext-formatted message to the output.
3801 * Like addWikiMsg() except the parameters are taken as an array
3802 * instead of a variable argument list.
3804 * @param string $name
3805 * @param array $args
3807 public function addWikiMsgArray( $name, $args ) {
3808 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3812 * This function takes a number of message/argument specifications, wraps them in
3813 * some overall structure, and then parses the result and adds it to the output.
3815 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3816 * and so on. The subsequent arguments may be either
3817 * 1) strings, in which case they are message names, or
3818 * 2) arrays, in which case, within each array, the first element is the message
3819 * name, and subsequent elements are the parameters to that message.
3821 * Don't use this for messages that are not in the user's interface language.
3825 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3829 * $wgOut->addWikiText( "<div class='error'>\n"
3830 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3832 * The newline after the opening div is needed in some wikitext. See T21226.
3834 * @param string $wrap
3836 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3837 $msgSpecs = func_get_args();
3838 array_shift( $msgSpecs );
3839 $msgSpecs = array_values( $msgSpecs );
3841 foreach ( $msgSpecs as $n => $spec ) {
3842 if ( is_array( $spec ) ) {
3844 $name = array_shift( $args );
3845 if ( isset( $args['options'] ) ) {
3846 unset( $args['options'] );
3848 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3856 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3858 $this->addWikiText( $s );
3862 * Whether the output has a table of contents
3866 public function isTOCEnabled() {
3867 return $this->mEnableTOC
;
3871 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3874 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3876 public function enableSectionEditLinks( $flag = true ) {
3877 wfDeprecated( __METHOD__
, '1.31' );
3883 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3885 public function sectionEditLinksEnabled() {
3886 wfDeprecated( __METHOD__
, '1.31' );
3891 * Helper function to setup the PHP implementation of OOUI to use in this request.
3894 * @param String $skinName The Skin name to determine the correct OOUI theme
3895 * @param String $dir Language direction
3897 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3898 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3899 $theme = $themes[$skinName] ??
$themes['default'];
3900 // For example, 'OOUI\WikimediaUITheme'.
3901 $themeClass = "OOUI\\{$theme}Theme";
3902 OOUI\Theme
::setSingleton( new $themeClass() );
3903 OOUI\Element
::setDefaultDir( $dir );
3907 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3908 * MediaWiki and this OutputPage instance.
3912 public function enableOOUI() {
3914 strtolower( $this->getSkin()->getSkinName() ),
3915 $this->getLanguage()->getDir()
3917 $this->addModuleStyles( [
3918 'oojs-ui-core.styles',
3919 'oojs-ui.styles.indicators',
3920 'oojs-ui.styles.textures',
3921 'mediawiki.widgets.styles',
3922 'oojs-ui.styles.icons-content',
3923 'oojs-ui.styles.icons-alerts',
3924 'oojs-ui.styles.icons-interactions',
3929 * Add Link headers for preloading the wiki's logo.
3933 protected function addLogoPreloadLinkHeaders() {
3934 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3940 if ( !is_array( $logo ) ) {
3941 // No media queries required if we only have one variant
3942 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3946 if ( isset( $logo['svg'] ) ) {
3947 // No media queries required if we only have a 1x and svg variant
3948 // because all preload-capable browsers support SVGs
3949 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3953 foreach ( $logo as $dppx => $src ) {
3954 // Keys are in this format: "1.5x"
3955 $dppx = substr( $dppx, 0, -1 );
3956 $logosPerDppx[$dppx] = $src;
3959 // Because PHP can't have floats as array keys
3960 uksort( $logosPerDppx, function ( $a , $b ) {
3961 $a = floatval( $a );
3962 $b = floatval( $b );
3963 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3967 foreach ( $logosPerDppx as $dppx => $src ) {
3968 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3971 $logosCount = count( $logos );
3972 // Logic must match ResourceLoaderSkinModule:
3973 // - 1x applies to resolution < 1.5dppx
3974 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3975 // - 2x applies to resolution >= 2dppx
3976 // Note that min-resolution and max-resolution are both inclusive.
3977 for ( $i = 0; $i < $logosCount; $i++
) {
3980 // min-resolution is ">=" (larger than or equal to)
3981 // "not min-resolution" is essentially "<"
3982 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3983 } elseif ( $i !== $logosCount - 1 ) {
3985 // Media query expressions can only apply "not" to the entire expression
3986 // (e.g. can't express ">= 1.5 and not >= 2).
3987 // Workaround: Use <= 1.9999 in place of < 2.
3988 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
3989 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3990 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
3993 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
3996 $this->addLinkHeader(
3997 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
4003 * Get (and set if not yet set) the CSP nonce.
4005 * This value needs to be included in any <script> tags on the
4008 * @return string|bool Nonce or false to mean don't output nonce
4011 public function getCSPNonce() {
4012 if ( !ContentSecurityPolicy
::isEnabled( $this->getConfig() ) ) {
4015 if ( $this->CSPNonce
=== null ) {
4016 // XXX It might be expensive to generate randomness
4017 // on every request, on Windows.
4018 $rand = random_bytes( 15 );
4019 $this->CSPNonce
= base64_encode( $rand );
4021 return $this->CSPNonce
;