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 out of skins/common, or a given relative path.
467 * Internal use only. Use OutputPage::addModules() if possible.
469 * @param string $file Filename in skins/common or complete on-server path
471 * @param string $version Style version of the file. Defaults to $wgStyleVersion
473 public function addScriptFile( $file, $version = null ) {
474 // See if $file parameter is an absolute URL or begins with a slash
475 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
478 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
480 if ( is_null( $version ) ) {
481 $version = $this->getConfig()->get( 'StyleVersion' );
483 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ), $this->getCSPNonce() ) );
487 * Add a self-contained script tag with the given contents
488 * Internal use only. Use OutputPage::addModules() if possible.
490 * @param string $script JavaScript text, no script tags
492 public function addInlineScript( $script ) {
493 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
497 * Filter an array of modules to remove insufficiently trustworthy members, and modules
498 * which are no longer registered (eg a page is cached before an extension is disabled)
499 * @param array $modules
500 * @param string|null $position Unused
501 * @param string $type
504 protected function filterModules( array $modules, $position = null,
505 $type = ResourceLoaderModule
::TYPE_COMBINED
507 $resourceLoader = $this->getResourceLoader();
508 $filteredModules = [];
509 foreach ( $modules as $val ) {
510 $module = $resourceLoader->getModule( $val );
511 if ( $module instanceof ResourceLoaderModule
512 && $module->getOrigin() <= $this->getAllowedModules( $type )
514 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
515 $this->warnModuleTargetFilter( $module->getName() );
518 $filteredModules[] = $val;
521 return $filteredModules;
524 private function warnModuleTargetFilter( $moduleName ) {
525 static $warnings = [];
526 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
529 $warnings[$this->mTarget
][$moduleName] = true;
530 $this->getResourceLoader()->getLogger()->debug(
531 'Module "{module}" not loadable on target "{target}".',
533 'module' => $moduleName,
534 'target' => $this->mTarget
,
540 * Get the list of modules to include on this page
542 * @param bool $filter Whether to filter out insufficiently trustworthy modules
543 * @param string|null $position Unused
544 * @param string $param
545 * @param string $type
546 * @return array Array of module names
548 public function getModules( $filter = false, $position = null, $param = 'mModules',
549 $type = ResourceLoaderModule
::TYPE_COMBINED
551 $modules = array_values( array_unique( $this->$param ) );
553 ?
$this->filterModules( $modules, null, $type )
558 * Load one or more ResourceLoader modules on this page.
560 * @param string|array $modules Module name (string) or array of module names
562 public function addModules( $modules ) {
563 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
567 * Get the list of script-only modules to load on this page.
569 * @param bool $filter
570 * @param string|null $position Unused
571 * @return array Array of module names
573 public function getModuleScripts( $filter = false, $position = null ) {
574 return $this->getModules( $filter, null, 'mModuleScripts',
575 ResourceLoaderModule
::TYPE_SCRIPTS
580 * Load the scripts of one or more ResourceLoader modules, on this page.
582 * This method exists purely to provide the legacy behaviour of loading
583 * a module's scripts in the global scope, and without dependency resolution.
584 * See <https://phabricator.wikimedia.org/T188689>.
586 * @deprecated since 1.31 Use addModules() instead.
587 * @param string|array $modules Module name (string) or array of module names
589 public function addModuleScripts( $modules ) {
590 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
594 * Get the list of style-only modules to load on this page.
596 * @param bool $filter
597 * @param string|null $position Unused
598 * @return array Array of module names
600 public function getModuleStyles( $filter = false, $position = null ) {
601 return $this->getModules( $filter, null, 'mModuleStyles',
602 ResourceLoaderModule
::TYPE_STYLES
607 * Load the styles of one or more ResourceLoader modules on this page.
609 * Module styles added through this function will be loaded as a stylesheet,
610 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
611 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
613 * @param string|array $modules Module name (string) or array of module names
615 public function addModuleStyles( $modules ) {
616 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
620 * @return null|string ResourceLoader target
622 public function getTarget() {
623 return $this->mTarget
;
627 * Sets ResourceLoader target for load.php links. If null, will be omitted
629 * @param string|null $target
631 public function setTarget( $target ) {
632 $this->mTarget
= $target;
636 * Add a mapping from a LinkTarget to a Content, for things like page preview.
637 * @see self::addContentOverrideCallback()
639 * @param LinkTarget $target
640 * @param Content $content
642 public function addContentOverride( LinkTarget
$target, Content
$content ) {
643 if ( !$this->contentOverrides
) {
644 // Register a callback for $this->contentOverrides on the first call
645 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
646 $key = $target->getNamespace() . ':' . $target->getDBkey();
647 return isset( $this->contentOverrides
[$key] )
648 ?
$this->contentOverrides
[$key]
653 $key = $target->getNamespace() . ':' . $target->getDBkey();
654 $this->contentOverrides
[$key] = $content;
658 * Add a callback for mapping from a Title to a Content object, for things
660 * @see ResourceLoaderContext::getContentOverrideCallback()
662 * @param callable $callback
664 public function addContentOverrideCallback( callable
$callback ) {
665 $this->contentOverrideCallbacks
[] = $callback;
669 * Get an array of head items
673 function getHeadItemsArray() {
674 return $this->mHeadItems
;
678 * Add or replace a head item to the output
680 * Whenever possible, use more specific options like ResourceLoader modules,
681 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
682 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
683 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
684 * This would be your very LAST fallback.
686 * @param string $name Item name
687 * @param string $value Raw HTML
689 public function addHeadItem( $name, $value ) {
690 $this->mHeadItems
[$name] = $value;
694 * Add one or more head items to the output
697 * @param string|string[] $values Raw HTML
699 public function addHeadItems( $values ) {
700 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
704 * Check if the header item $name is already set
706 * @param string $name Item name
709 public function hasHeadItem( $name ) {
710 return isset( $this->mHeadItems
[$name] );
714 * Add a class to the <body> element
717 * @param string|string[] $classes One or more classes to add
719 public function addBodyClasses( $classes ) {
720 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
724 * Set whether the output should only contain the body of the article,
725 * without any skin, sidebar, etc.
726 * Used e.g. when calling with "action=render".
728 * @param bool $only Whether to output only the body of the article
730 public function setArticleBodyOnly( $only ) {
731 $this->mArticleBodyOnly
= $only;
735 * Return whether the output will contain only the body of the article
739 public function getArticleBodyOnly() {
740 return $this->mArticleBodyOnly
;
744 * Set an additional output property
747 * @param string $name
748 * @param mixed $value
750 public function setProperty( $name, $value ) {
751 $this->mProperties
[$name] = $value;
755 * Get an additional output property
758 * @param string $name
759 * @return mixed Property value or null if not found
761 public function getProperty( $name ) {
762 if ( isset( $this->mProperties
[$name] ) ) {
763 return $this->mProperties
[$name];
770 * checkLastModified tells the client to use the client-cached page if
771 * possible. If successful, the OutputPage is disabled so that
772 * any future call to OutputPage->output() have no effect.
774 * Side effect: sets mLastModified for Last-Modified header
776 * @param string $timestamp
778 * @return bool True if cache-ok headers was sent.
780 public function checkLastModified( $timestamp ) {
781 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
782 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
785 $config = $this->getConfig();
786 if ( !$config->get( 'CachePages' ) ) {
787 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
791 $timestamp = wfTimestamp( TS_MW
, $timestamp );
793 'page' => $timestamp,
794 'user' => $this->getUser()->getTouched(),
795 'epoch' => $config->get( 'CacheEpoch' )
797 if ( $config->get( 'UseSquid' ) ) {
798 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
800 $config->get( 'SquidMaxage' )
803 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
805 $maxModified = max( $modifiedTimes );
806 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
808 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
809 if ( $clientHeader === false ) {
810 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
814 # IE sends sizes after the date like this:
815 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
816 # this breaks strtotime().
817 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
819 Wikimedia\
suppressWarnings(); // E_STRICT system time bitching
820 $clientHeaderTime = strtotime( $clientHeader );
821 Wikimedia\restoreWarnings
();
822 if ( !$clientHeaderTime ) {
824 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
827 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
831 foreach ( $modifiedTimes as $name => $value ) {
832 if ( $info !== '' ) {
835 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
838 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
839 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
840 wfDebug( __METHOD__
. ": effective Last-Modified: " .
841 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
842 if ( $clientHeaderTime < $maxModified ) {
843 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
848 # Give a 304 Not Modified response code and disable body output
849 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
850 ini_set( 'zlib.output_compression', 0 );
851 $this->getRequest()->response()->statusHeader( 304 );
852 $this->sendCacheControl();
855 // Don't output a compressed blob when using ob_gzhandler;
856 // it's technically against HTTP spec and seems to confuse
857 // Firefox when the response gets split over two packets.
858 wfClearOutputBuffers();
864 * @param int $reqTime Time of request (eg. now)
865 * @param int $maxAge Cache TTL in seconds
866 * @return int Timestamp
868 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
869 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
870 // because even if the wiki page content hasn't changed since, static
871 // resources may have changed (skin HTML, interface messages, urls, etc.)
872 // and must roll-over in a timely manner (T46570)
873 return $reqTime - $maxAge;
877 * Override the last modified timestamp
879 * @param string $timestamp New timestamp, in a format readable by
882 public function setLastModified( $timestamp ) {
883 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
887 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
889 * @param string $policy The literal string to output as the contents of
890 * the meta tag. Will be parsed according to the spec and output in
894 public function setRobotPolicy( $policy ) {
895 $policy = Article
::formatRobotPolicy( $policy );
897 if ( isset( $policy['index'] ) ) {
898 $this->setIndexPolicy( $policy['index'] );
900 if ( isset( $policy['follow'] ) ) {
901 $this->setFollowPolicy( $policy['follow'] );
906 * Set the index policy for the page, but leave the follow policy un-
909 * @param string $policy Either 'index' or 'noindex'.
912 public function setIndexPolicy( $policy ) {
913 $policy = trim( $policy );
914 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
915 $this->mIndexPolicy
= $policy;
920 * Set the follow policy for the page, but leave the index policy un-
923 * @param string $policy Either 'follow' or 'nofollow'.
926 public function setFollowPolicy( $policy ) {
927 $policy = trim( $policy );
928 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
929 $this->mFollowPolicy
= $policy;
934 * Set the new value of the "action text", this will be added to the
935 * "HTML title", separated from it with " - ".
937 * @param string $text New value of the "action text"
939 public function setPageTitleActionText( $text ) {
940 $this->mPageTitleActionText
= $text;
944 * Get the value of the "action text"
948 public function getPageTitleActionText() {
949 return $this->mPageTitleActionText
;
953 * "HTML title" means the contents of "<title>".
954 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
956 * @param string|Message $name
958 public function setHTMLTitle( $name ) {
959 if ( $name instanceof Message
) {
960 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
962 $this->mHTMLtitle
= $name;
967 * Return the "HTML title", i.e. the content of the "<title>" tag.
971 public function getHTMLTitle() {
972 return $this->mHTMLtitle
;
976 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
980 public function setRedirectedFrom( $t ) {
981 $this->mRedirectedFrom
= $t;
985 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
986 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
987 * but not bad tags like \<script\>. This function automatically sets
988 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
989 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
990 * good tags like \<i\> will be dropped entirely.
992 * @param string|Message $name
994 public function setPageTitle( $name ) {
995 if ( $name instanceof Message
) {
996 $name = $name->setContext( $this->getContext() )->text();
999 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
1000 # but leave "<i>foobar</i>" alone
1001 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
1002 $this->mPagetitle
= $nameWithTags;
1004 # change "<i>foo&bar</i>" to "foo&bar"
1005 $this->setHTMLTitle(
1006 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
1007 ->inContentLanguage()
1012 * Return the "page title", i.e. the content of the \<h1\> tag.
1016 public function getPageTitle() {
1017 return $this->mPagetitle
;
1021 * Set the Title object to use
1025 public function setTitle( Title
$t ) {
1026 $this->getContext()->setTitle( $t );
1030 * Replace the subtitle with $str
1032 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1034 public function setSubtitle( $str ) {
1035 $this->clearSubtitle();
1036 $this->addSubtitle( $str );
1040 * Add $str to the subtitle
1042 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1044 public function addSubtitle( $str ) {
1045 if ( $str instanceof Message
) {
1046 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1048 $this->mSubtitle
[] = $str;
1053 * Build message object for a subtitle containing a backlink to a page
1055 * @param Title $title Title to link to
1056 * @param array $query Array of additional parameters to include in the link
1060 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1061 if ( $title->isRedirect() ) {
1062 $query['redirect'] = 'no';
1064 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1065 return wfMessage( 'backlinksubtitle' )
1066 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1070 * Add a subtitle containing a backlink to a page
1072 * @param Title $title Title to link to
1073 * @param array $query Array of additional parameters to include in the link
1075 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1076 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1080 * Clear the subtitles
1082 public function clearSubtitle() {
1083 $this->mSubtitle
= [];
1091 public function getSubtitle() {
1092 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1096 * Set the page as printable, i.e. it'll be displayed with all
1097 * print styles included
1099 public function setPrintable() {
1100 $this->mPrintable
= true;
1104 * Return whether the page is "printable"
1108 public function isPrintable() {
1109 return $this->mPrintable
;
1113 * Disable output completely, i.e. calling output() will have no effect
1115 public function disable() {
1116 $this->mDoNothing
= true;
1120 * Return whether the output will be completely disabled
1124 public function isDisabled() {
1125 return $this->mDoNothing
;
1129 * Show an "add new section" link?
1133 public function showNewSectionLink() {
1134 return $this->mNewSectionLink
;
1138 * Forcibly hide the new section link?
1142 public function forceHideNewSectionLink() {
1143 return $this->mHideNewSectionLink
;
1147 * Add or remove feed links in the page header
1148 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1149 * for the new version
1150 * @see addFeedLink()
1152 * @param bool $show True: add default feeds, false: remove all feeds
1154 public function setSyndicated( $show = true ) {
1156 $this->setFeedAppendQuery( false );
1158 $this->mFeedLinks
= [];
1163 * Add default feeds to the page header
1164 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1165 * for the new version
1166 * @see addFeedLink()
1168 * @param string $val Query to append to feed links or false to output
1171 public function setFeedAppendQuery( $val ) {
1172 $this->mFeedLinks
= [];
1174 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1175 $query = "feed=$type";
1176 if ( is_string( $val ) ) {
1177 $query .= '&' . $val;
1179 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1184 * Add a feed link to the page header
1186 * @param string $format Feed type, should be a key of $wgFeedClasses
1187 * @param string $href URL
1189 public function addFeedLink( $format, $href ) {
1190 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1191 $this->mFeedLinks
[$format] = $href;
1196 * Should we output feed links for this page?
1199 public function isSyndicated() {
1200 return count( $this->mFeedLinks
) > 0;
1204 * Return URLs for each supported syndication format for this page.
1205 * @return array Associating format keys with URLs
1207 public function getSyndicationLinks() {
1208 return $this->mFeedLinks
;
1212 * Will currently always return null
1216 public function getFeedAppendQuery() {
1217 return $this->mFeedLinksAppendQuery
;
1221 * Set whether the displayed content is related to the source of the
1222 * corresponding article on the wiki
1223 * Setting true will cause the change "article related" toggle to true
1227 public function setArticleFlag( $v ) {
1228 $this->mIsarticle
= $v;
1230 $this->mIsArticleRelated
= $v;
1235 * Return whether the content displayed page is related to the source of
1236 * the corresponding article on the wiki
1240 public function isArticle() {
1241 return $this->mIsarticle
;
1245 * Set whether this page is related an article on the wiki
1246 * Setting false will cause the change of "article flag" toggle to false
1250 public function setArticleRelated( $v ) {
1251 $this->mIsArticleRelated
= $v;
1253 $this->mIsarticle
= false;
1258 * Return whether this page is related an article on the wiki
1262 public function isArticleRelated() {
1263 return $this->mIsArticleRelated
;
1267 * Add new language links
1269 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1270 * (e.g. 'fr:Test page')
1272 public function addLanguageLinks( array $newLinkArray ) {
1273 $this->mLanguageLinks +
= $newLinkArray;
1277 * Reset the language links and add new language links
1279 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1280 * (e.g. 'fr:Test page')
1282 public function setLanguageLinks( array $newLinkArray ) {
1283 $this->mLanguageLinks
= $newLinkArray;
1287 * Get the list of language links
1289 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1291 public function getLanguageLinks() {
1292 return $this->mLanguageLinks
;
1296 * Add an array of categories, with names in the keys
1298 * @param array $categories Mapping category name => sort key
1300 public function addCategoryLinks( array $categories ) {
1303 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1307 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1309 # Set all the values to 'normal'.
1310 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1312 # Mark hidden categories
1313 foreach ( $res as $row ) {
1314 if ( isset( $row->pp_value
) ) {
1315 $categories[$row->page_title
] = 'hidden';
1319 // Avoid PHP 7.1 warning of passing $this by reference
1320 $outputPage = $this;
1321 # Add the remaining categories to the skin
1323 'OutputPageMakeCategoryLinks',
1324 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1326 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1327 foreach ( $categories as $category => $type ) {
1328 // array keys will cast numeric category names to ints, so cast back to string
1329 $category = (string)$category;
1330 $origcategory = $category;
1331 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1335 $wgContLang->findVariantLink( $category, $title, true );
1336 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1339 $text = $wgContLang->convertHtml( $title->getText() );
1340 $this->mCategories
[$type][] = $title->getText();
1341 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1347 * @param array $categories
1348 * @return bool|ResultWrapper
1350 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1351 # Add the links to a LinkBatch
1352 $arr = [ NS_CATEGORY
=> $categories ];
1353 $lb = new LinkBatch
;
1354 $lb->setArray( $arr );
1356 # Fetch existence plus the hiddencat property
1357 $dbr = wfGetDB( DB_REPLICA
);
1358 $fields = array_merge(
1359 LinkCache
::getSelectFields(),
1360 [ 'page_namespace', 'page_title', 'pp_value' ]
1363 $res = $dbr->select( [ 'page', 'page_props' ],
1365 $lb->constructSet( 'page', $dbr ),
1368 [ 'page_props' => [ 'LEFT JOIN', [
1369 'pp_propname' => 'hiddencat',
1374 # Add the results to the link cache
1375 $lb->addResultToCache( LinkCache
::singleton(), $res );
1381 * Reset the category links (but not the category list) and add $categories
1383 * @param array $categories Mapping category name => sort key
1385 public function setCategoryLinks( array $categories ) {
1386 $this->mCategoryLinks
= [];
1387 $this->addCategoryLinks( $categories );
1391 * Get the list of category links, in a 2-D array with the following format:
1392 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1393 * hidden categories) and $link a HTML fragment with a link to the category
1398 public function getCategoryLinks() {
1399 return $this->mCategoryLinks
;
1403 * Get the list of category names this page belongs to.
1405 * @param string $type The type of categories which should be returned. Possible values:
1406 * * all: all categories of all types
1407 * * hidden: only the hidden categories
1408 * * normal: all categories, except hidden categories
1409 * @return array Array of strings
1411 public function getCategories( $type = 'all' ) {
1412 if ( $type === 'all' ) {
1413 $allCategories = [];
1414 foreach ( $this->mCategories
as $categories ) {
1415 $allCategories = array_merge( $allCategories, $categories );
1417 return $allCategories;
1419 if ( !isset( $this->mCategories
[$type] ) ) {
1420 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1422 return $this->mCategories
[$type];
1426 * Add an array of indicators, with their identifiers as array
1427 * keys and HTML contents as values.
1429 * In case of duplicate keys, existing values are overwritten.
1431 * @param array $indicators
1434 public function setIndicators( array $indicators ) {
1435 $this->mIndicators
= $indicators +
$this->mIndicators
;
1436 // Keep ordered by key
1437 ksort( $this->mIndicators
);
1441 * Get the indicators associated with this page.
1443 * The array will be internally ordered by item keys.
1445 * @return array Keys: identifiers, values: HTML contents
1448 public function getIndicators() {
1449 return $this->mIndicators
;
1453 * Adds help link with an icon via page indicators.
1454 * Link target can be overridden by a local message containing a wikilink:
1455 * the message key is: lowercase action or special page name + '-helppage'.
1456 * @param string $to Target MediaWiki.org page title or encoded URL.
1457 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1460 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1461 $this->addModuleStyles( 'mediawiki.helplink' );
1462 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1464 if ( $overrideBaseUrl ) {
1467 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1468 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1471 $link = Html
::rawElement(
1475 'target' => '_blank',
1476 'class' => 'mw-helplink',
1481 $this->setIndicators( [ 'mw-helplink' => $link ] );
1485 * Do not allow scripts which can be modified by wiki users to load on this page;
1486 * only allow scripts bundled with, or generated by, the software.
1487 * Site-wide styles are controlled by a config setting, since they can be
1488 * used to create a custom skin/theme, but not user-specific ones.
1490 * @todo this should be given a more accurate name
1492 public function disallowUserJs() {
1493 $this->reduceAllowedModules(
1494 ResourceLoaderModule
::TYPE_SCRIPTS
,
1495 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1498 // Site-wide styles are controlled by a config setting, see T73621
1499 // for background on why. User styles are never allowed.
1500 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1501 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1503 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1505 $this->reduceAllowedModules(
1506 ResourceLoaderModule
::TYPE_STYLES
,
1512 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1513 * @see ResourceLoaderModule::$origin
1514 * @param string $type ResourceLoaderModule TYPE_ constant
1515 * @return int ResourceLoaderModule ORIGIN_ class constant
1517 public function getAllowedModules( $type ) {
1518 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1519 return min( array_values( $this->mAllowedModules
) );
1521 return isset( $this->mAllowedModules
[$type] )
1522 ?
$this->mAllowedModules
[$type]
1523 : ResourceLoaderModule
::ORIGIN_ALL
;
1528 * Limit the highest level of CSS/JS untrustworthiness allowed.
1530 * If passed the same or a higher level than the current level of untrustworthiness set, the
1531 * level will remain unchanged.
1533 * @param string $type
1534 * @param int $level ResourceLoaderModule class constant
1536 public function reduceAllowedModules( $type, $level ) {
1537 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1541 * Prepend $text to the body HTML
1543 * @param string $text HTML
1545 public function prependHTML( $text ) {
1546 $this->mBodytext
= $text . $this->mBodytext
;
1550 * Append $text to the body HTML
1552 * @param string $text HTML
1554 public function addHTML( $text ) {
1555 $this->mBodytext
.= $text;
1559 * Shortcut for adding an Html::element via addHTML.
1563 * @param string $element
1564 * @param array $attribs
1565 * @param string $contents
1567 public function addElement( $element, array $attribs = [], $contents = '' ) {
1568 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1572 * Clear the body HTML
1574 public function clearHTML() {
1575 $this->mBodytext
= '';
1581 * @return string HTML
1583 public function getHTML() {
1584 return $this->mBodytext
;
1588 * Get/set the ParserOptions object to use for wikitext parsing
1590 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1591 * current ParserOption object. This parameter is deprecated since 1.31.
1592 * @return ParserOptions
1594 public function parserOptions( $options = null ) {
1595 if ( $options !== null ) {
1596 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1599 if ( $options !== null && !empty( $options->isBogus
) ) {
1600 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1601 // been changed somehow, and keep it if so.
1602 $anonPO = ParserOptions
::newFromAnon();
1603 $anonPO->setAllowUnsafeRawHtml( false );
1604 if ( !$options->matches( $anonPO ) ) {
1605 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1606 $options->isBogus
= false;
1610 if ( !$this->mParserOptions
) {
1611 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1612 // $wgUser isn't unstubbable yet, so don't try to get a
1613 // ParserOptions for it. And don't cache this ParserOptions
1615 $po = ParserOptions
::newFromAnon();
1616 $po->setAllowUnsafeRawHtml( false );
1617 $po->isBogus
= true;
1618 if ( $options !== null ) {
1619 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1624 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1625 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1628 if ( $options !== null && !empty( $options->isBogus
) ) {
1629 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1631 return wfSetVar( $this->mParserOptions
, null, true );
1633 return wfSetVar( $this->mParserOptions
, $options );
1638 * Set the revision ID which will be seen by the wiki text parser
1639 * for things such as embedded {{REVISIONID}} variable use.
1641 * @param int|null $revid An positive integer, or null
1642 * @return mixed Previous value
1644 public function setRevisionId( $revid ) {
1645 $val = is_null( $revid ) ?
null : intval( $revid );
1646 return wfSetVar( $this->mRevisionId
, $val );
1650 * Get the displayed revision ID
1654 public function getRevisionId() {
1655 return $this->mRevisionId
;
1659 * Set the timestamp of the revision which will be displayed. This is used
1660 * to avoid a extra DB call in Skin::lastModified().
1662 * @param string|null $timestamp
1663 * @return mixed Previous value
1665 public function setRevisionTimestamp( $timestamp ) {
1666 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1670 * Get the timestamp of displayed revision.
1671 * This will be null if not filled by setRevisionTimestamp().
1673 * @return string|null
1675 public function getRevisionTimestamp() {
1676 return $this->mRevisionTimestamp
;
1680 * Set the displayed file version
1682 * @param File|bool $file
1683 * @return mixed Previous value
1685 public function setFileVersion( $file ) {
1687 if ( $file instanceof File
&& $file->exists() ) {
1688 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1690 return wfSetVar( $this->mFileVersion
, $val, true );
1694 * Get the displayed file version
1696 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1698 public function getFileVersion() {
1699 return $this->mFileVersion
;
1703 * Get the templates used on this page
1705 * @return array (namespace => dbKey => revId)
1708 public function getTemplateIds() {
1709 return $this->mTemplateIds
;
1713 * Get the files used on this page
1715 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1718 public function getFileSearchOptions() {
1719 return $this->mImageTimeKeys
;
1723 * Convert wikitext to HTML and add it to the buffer
1724 * Default assumes that the current page title will be used.
1726 * @param string $text
1727 * @param bool $linestart Is this the start of a line?
1728 * @param bool $interface Is this text in the user interface language?
1729 * @throws MWException
1731 public function addWikiText( $text, $linestart = true, $interface = true ) {
1732 $title = $this->getTitle(); // Work around E_STRICT
1734 throw new MWException( 'Title is null' );
1736 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1740 * Add wikitext with a custom Title object
1742 * @param string $text Wikitext
1743 * @param Title &$title
1744 * @param bool $linestart Is this the start of a line?
1746 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1747 $this->addWikiTextTitle( $text, $title, $linestart );
1751 * Add wikitext with a custom Title object and tidy enabled.
1753 * @param string $text Wikitext
1754 * @param Title &$title
1755 * @param bool $linestart Is this the start of a line?
1757 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1758 $this->addWikiTextTitle( $text, $title, $linestart, true );
1762 * Add wikitext with tidy enabled
1764 * @param string $text Wikitext
1765 * @param bool $linestart Is this the start of a line?
1767 public function addWikiTextTidy( $text, $linestart = true ) {
1768 $title = $this->getTitle();
1769 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1773 * Add wikitext with a custom Title object
1775 * @param string $text Wikitext
1776 * @param Title $title
1777 * @param bool $linestart Is this the start of a line?
1778 * @param bool $tidy Whether to use tidy
1779 * @param bool $interface Whether it is an interface message
1780 * (for example disables conversion)
1782 public function addWikiTextTitle( $text, Title
$title, $linestart,
1783 $tidy = false, $interface = false
1787 $popts = $this->parserOptions();
1788 $oldTidy = $popts->setTidy( $tidy );
1789 $popts->setInterfaceMessage( (bool)$interface );
1791 $parserOutput = $wgParser->getFreshParser()->parse(
1792 $text, $title, $popts,
1793 $linestart, true, $this->mRevisionId
1796 $popts->setTidy( $oldTidy );
1798 $this->addParserOutput( $parserOutput, [
1799 'enableSectionEditLinks' => false,
1804 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1805 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1809 * @param ParserOutput $parserOutput
1811 public function addParserOutputMetadata( $parserOutput ) {
1812 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1813 $this->addCategoryLinks( $parserOutput->getCategories() );
1814 $this->setIndicators( $parserOutput->getIndicators() );
1815 $this->mNewSectionLink
= $parserOutput->getNewSection();
1816 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1818 if ( !$parserOutput->isCacheable() ) {
1819 $this->enableClientCache( false );
1821 $this->mNoGallery
= $parserOutput->getNoGallery();
1822 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1823 $this->addModules( $parserOutput->getModules() );
1824 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1825 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1826 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1827 $this->mPreventClickjacking
= $this->mPreventClickjacking
1828 ||
$parserOutput->preventClickjacking();
1830 // Template versioning...
1831 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1832 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1833 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1835 $this->mTemplateIds
[$ns] = $dbks;
1838 // File versioning...
1839 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1840 $this->mImageTimeKeys
[$dbk] = $data;
1843 // Hooks registered in the object
1844 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1845 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1846 list( $hookName, $data ) = $hookInfo;
1847 if ( isset( $parserOutputHooks[$hookName] ) ) {
1848 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1852 // Enable OOUI if requested via ParserOutput
1853 if ( $parserOutput->getEnableOOUI() ) {
1854 $this->enableOOUI();
1857 // Include parser limit report
1858 if ( !$this->limitReportJSData
) {
1859 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1862 // Link flags are ignored for now, but may in the future be
1863 // used to mark individual language links.
1865 // Avoid PHP 7.1 warning of passing $this by reference
1866 $outputPage = $this;
1867 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1868 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1870 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1871 // so that extensions may modify ParserOutput to toggle TOC.
1872 // This cannot be moved to addParserOutputText because that is not
1873 // called by EditPage for Preview.
1874 if ( $parserOutput->getTOCHTML() ) {
1875 $this->mEnableTOC
= true;
1880 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1881 * ParserOutput object, without any other metadata.
1884 * @param ParserOutput $parserOutput
1885 * @param array $poOptions Options to ParserOutput::getText()
1887 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1888 $this->addParserOutputText( $parserOutput, $poOptions );
1890 $this->addModules( $parserOutput->getModules() );
1891 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1892 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1894 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1898 * Add the HTML associated with a ParserOutput object, without any metadata.
1901 * @param ParserOutput $parserOutput
1902 * @param array $poOptions Options to ParserOutput::getText()
1904 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1905 $text = $parserOutput->getText( $poOptions );
1906 // Avoid PHP 7.1 warning of passing $this by reference
1907 $outputPage = $this;
1908 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1909 $this->addHTML( $text );
1913 * Add everything from a ParserOutput object.
1915 * @param ParserOutput $parserOutput
1916 * @param array $poOptions Options to ParserOutput::getText()
1918 function addParserOutput( $parserOutput, $poOptions = [] ) {
1919 $this->addParserOutputMetadata( $parserOutput );
1920 $this->addParserOutputText( $parserOutput, $poOptions );
1924 * Add the output of a QuickTemplate to the output buffer
1926 * @param QuickTemplate &$template
1928 public function addTemplate( &$template ) {
1929 $this->addHTML( $template->getHTML() );
1933 * Parse wikitext and return the HTML.
1935 * @param string $text
1936 * @param bool $linestart Is this the start of a line?
1937 * @param bool $interface Use interface language ($wgLang instead of
1938 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1939 * This also disables LanguageConverter.
1940 * @param Language $language Target language object, will override $interface
1941 * @throws MWException
1942 * @return string HTML
1944 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1947 if ( is_null( $this->getTitle() ) ) {
1948 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1951 $popts = $this->parserOptions();
1953 $popts->setInterfaceMessage( true );
1955 if ( $language !== null ) {
1956 $oldLang = $popts->setTargetLanguage( $language );
1959 $parserOutput = $wgParser->getFreshParser()->parse(
1960 $text, $this->getTitle(), $popts,
1961 $linestart, true, $this->mRevisionId
1965 $popts->setInterfaceMessage( false );
1967 if ( $language !== null ) {
1968 $popts->setTargetLanguage( $oldLang );
1971 return $parserOutput->getText( [
1972 'enableSectionEditLinks' => false,
1977 * Parse wikitext, strip paragraphs, and return the HTML.
1979 * @param string $text
1980 * @param bool $linestart Is this the start of a line?
1981 * @param bool $interface Use interface language ($wgLang instead of
1982 * $wgContLang) while parsing language sensitive magic
1983 * words like GRAMMAR and PLURAL
1984 * @return string HTML
1986 public function parseInline( $text, $linestart = true, $interface = false ) {
1987 $parsed = $this->parse( $text, $linestart, $interface );
1988 return Parser
::stripOuterParagraph( $parsed );
1992 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1994 * @param int $maxage Maximum cache time on the CDN, in seconds.
1996 public function setCdnMaxage( $maxage ) {
1997 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2001 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
2003 * @param int $maxage Maximum cache time on the CDN, in seconds
2006 public function lowerCdnMaxage( $maxage ) {
2007 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2008 $this->setCdnMaxage( $this->mCdnMaxage
);
2012 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2014 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2015 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2016 * TTL is 90% of the age of the object, subject to the min and max.
2018 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2019 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2020 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2021 * @return int TTL in seconds
2024 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2025 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2026 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2028 if ( $mtime === null ||
$mtime === false ) {
2029 return $minTTL; // entity does not exist
2032 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2033 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2034 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2036 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2038 return $adaptiveTTL;
2042 * Use enableClientCache(false) to force it to send nocache headers
2044 * @param bool $state
2048 public function enableClientCache( $state ) {
2049 return wfSetVar( $this->mEnableClientCache
, $state );
2053 * Get the list of cookies that will influence on the cache
2057 function getCacheVaryCookies() {
2059 if ( $cookies === null ) {
2060 $config = $this->getConfig();
2061 $cookies = array_merge(
2062 SessionManager
::singleton()->getVaryCookies(),
2066 $config->get( 'CacheVaryCookies' )
2068 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2074 * Check if the request has a cache-varying cookie header
2075 * If it does, it's very important that we don't allow public caching
2079 function haveCacheVaryCookies() {
2080 $request = $this->getRequest();
2081 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2082 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2083 wfDebug( __METHOD__
. ": found $cookieName\n" );
2087 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2092 * Add an HTTP header that will influence on the cache
2094 * @param string $header Header name
2095 * @param string[]|null $option Options for the Key header. See
2096 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2097 * for the list of valid options.
2099 public function addVaryHeader( $header, array $option = null ) {
2100 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2101 $this->mVaryHeader
[$header] = [];
2103 if ( !is_array( $option ) ) {
2106 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2110 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2111 * such as Accept-Encoding or Cookie
2115 public function getVaryHeader() {
2116 // If we vary on cookies, let's make sure it's always included here too.
2117 if ( $this->getCacheVaryCookies() ) {
2118 $this->addVaryHeader( 'Cookie' );
2121 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2122 $this->addVaryHeader( $header, $options );
2124 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2128 * Add an HTTP Link: header
2130 * @param string $header Header value
2132 public function addLinkHeader( $header ) {
2133 $this->mLinkHeader
[] = $header;
2137 * Return a Link: header. Based on the values of $mLinkHeader.
2141 public function getLinkHeader() {
2142 if ( !$this->mLinkHeader
) {
2146 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2150 * Get a complete Key header
2154 public function getKeyHeader() {
2155 $cvCookies = $this->getCacheVaryCookies();
2157 $cookiesOption = [];
2158 foreach ( $cvCookies as $cookieName ) {
2159 $cookiesOption[] = 'param=' . $cookieName;
2161 $this->addVaryHeader( 'Cookie', $cookiesOption );
2163 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2164 $this->addVaryHeader( $header, $options );
2168 foreach ( $this->mVaryHeader
as $header => $option ) {
2169 $newheader = $header;
2170 if ( is_array( $option ) && count( $option ) > 0 ) {
2171 $newheader .= ';' . implode( ';', $option );
2173 $headers[] = $newheader;
2175 $key = 'Key: ' . implode( ',', $headers );
2181 * T23672: Add Accept-Language to Vary and Key headers
2182 * if there's no 'variant' parameter existed in GET.
2185 * /w/index.php?title=Main_page should always be served; but
2186 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2188 function addAcceptLanguage() {
2189 $title = $this->getTitle();
2190 if ( !$title instanceof Title
) {
2194 $lang = $title->getPageLanguage();
2195 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2196 $variants = $lang->getVariants();
2198 foreach ( $variants as $variant ) {
2199 if ( $variant === $lang->getCode() ) {
2202 $aloption[] = 'substr=' . $variant;
2204 // IE and some other browsers use BCP 47 standards in
2205 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2206 // We should handle these too.
2207 $variantBCP47 = LanguageCode
::bcp47( $variant );
2208 if ( $variantBCP47 !== $variant ) {
2209 $aloption[] = 'substr=' . $variantBCP47;
2213 $this->addVaryHeader( 'Accept-Language', $aloption );
2218 * Set a flag which will cause an X-Frame-Options header appropriate for
2219 * edit pages to be sent. The header value is controlled by
2220 * $wgEditPageFrameOptions.
2222 * This is the default for special pages. If you display a CSRF-protected
2223 * form on an ordinary view page, then you need to call this function.
2225 * @param bool $enable
2227 public function preventClickjacking( $enable = true ) {
2228 $this->mPreventClickjacking
= $enable;
2232 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2233 * This can be called from pages which do not contain any CSRF-protected
2236 public function allowClickjacking() {
2237 $this->mPreventClickjacking
= false;
2241 * Get the prevent-clickjacking flag
2246 public function getPreventClickjacking() {
2247 return $this->mPreventClickjacking
;
2251 * Get the X-Frame-Options header value (without the name part), or false
2252 * if there isn't one. This is used by Skin to determine whether to enable
2253 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2255 * @return string|false
2257 public function getFrameOptions() {
2258 $config = $this->getConfig();
2259 if ( $config->get( 'BreakFrames' ) ) {
2261 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2262 return $config->get( 'EditPageFrameOptions' );
2268 * Send cache control HTTP headers
2270 public function sendCacheControl() {
2271 $response = $this->getRequest()->response();
2272 $config = $this->getConfig();
2274 $this->addVaryHeader( 'Cookie' );
2275 $this->addAcceptLanguage();
2277 # don't serve compressed data to clients who can't handle it
2278 # maintain different caches for logged-in users and non-logged in ones
2279 $response->header( $this->getVaryHeader() );
2281 if ( $config->get( 'UseKeyHeader' ) ) {
2282 $response->header( $this->getKeyHeader() );
2285 if ( $this->mEnableClientCache
) {
2287 $config->get( 'UseSquid' ) &&
2288 !$response->hasCookies() &&
2289 !SessionManager
::getGlobalSession()->isPersistent() &&
2290 !$this->isPrintable() &&
2291 $this->mCdnMaxage
!= 0 &&
2292 !$this->haveCacheVaryCookies()
2294 if ( $config->get( 'UseESI' ) ) {
2295 # We'll purge the proxy cache explicitly, but require end user agents
2296 # to revalidate against the proxy on each visit.
2297 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2298 wfDebug( __METHOD__
.
2299 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2300 # start with a shorter timeout for initial testing
2301 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2303 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2304 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2306 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2308 # We'll purge the proxy cache for anons explicitly, but require end user agents
2309 # to revalidate against the proxy on each visit.
2310 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2311 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2312 wfDebug( __METHOD__
.
2313 ": local proxy caching; {$this->mLastModified} **", 'private' );
2314 # start with a shorter timeout for initial testing
2315 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2316 $response->header( "Cache-Control: " .
2317 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2320 # We do want clients to cache if they can, but they *must* check for updates
2321 # on revisiting the page.
2322 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2323 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2324 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2326 if ( $this->mLastModified
) {
2327 $response->header( "Last-Modified: {$this->mLastModified}" );
2330 wfDebug( __METHOD__
. ": no caching **", 'private' );
2332 # In general, the absence of a last modified header should be enough to prevent
2333 # the client from using its cache. We send a few other things just to make sure.
2334 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2335 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2336 $response->header( 'Pragma: no-cache' );
2341 * Transfer styles and JavaScript modules from skin.
2343 * @param Skin $sk to load modules for
2345 public function loadSkinModules( $sk ) {
2346 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2347 if ( $group === 'styles' ) {
2348 foreach ( $modules as $key => $moduleMembers ) {
2349 $this->addModuleStyles( $moduleMembers );
2352 $this->addModules( $modules );
2358 * Finally, all the text has been munged and accumulated into
2359 * the object, let's actually output it:
2361 * @param bool $return Set to true to get the result as a string rather than sending it
2362 * @return string|null
2364 * @throws FatalError
2365 * @throws MWException
2367 public function output( $return = false ) {
2370 if ( $this->mDoNothing
) {
2371 return $return ?
'' : null;
2374 $response = $this->getRequest()->response();
2375 $config = $this->getConfig();
2377 if ( $this->mRedirect
!= '' ) {
2378 # Standards require redirect URLs to be absolute
2379 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2381 $redirect = $this->mRedirect
;
2382 $code = $this->mRedirectCode
;
2384 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2385 if ( $code == '301' ||
$code == '303' ) {
2386 if ( !$config->get( 'DebugRedirects' ) ) {
2387 $response->statusHeader( $code );
2389 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2391 if ( $config->get( 'VaryOnXFP' ) ) {
2392 $this->addVaryHeader( 'X-Forwarded-Proto' );
2394 $this->sendCacheControl();
2396 $response->header( "Content-Type: text/html; charset=utf-8" );
2397 if ( $config->get( 'DebugRedirects' ) ) {
2398 $url = htmlspecialchars( $redirect );
2399 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2400 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2401 print "</body>\n</html>\n";
2403 $response->header( 'Location: ' . $redirect );
2407 return $return ?
'' : null;
2408 } elseif ( $this->mStatusCode
) {
2409 $response->statusHeader( $this->mStatusCode
);
2412 # Buffer output; final headers may depend on later processing
2415 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2416 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2418 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2419 // jQuery etc. can work correctly.
2420 $response->header( 'X-UA-Compatible: IE=Edge' );
2422 if ( !$this->mArticleBodyOnly
) {
2423 $sk = $this->getSkin();
2425 if ( $sk->shouldPreloadLogo() ) {
2426 $this->addLogoPreloadLinkHeaders();
2430 $linkHeader = $this->getLinkHeader();
2431 if ( $linkHeader ) {
2432 $response->header( $linkHeader );
2435 // Prevent framing, if requested
2436 $frameOptions = $this->getFrameOptions();
2437 if ( $frameOptions ) {
2438 $response->header( "X-Frame-Options: $frameOptions" );
2441 ContentSecurityPolicy
::sendHeaders( $this );
2443 if ( $this->mArticleBodyOnly
) {
2444 echo $this->mBodytext
;
2446 // Enable safe mode if requested
2447 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2448 $this->disallowUserJs();
2451 $sk = $this->getSkin();
2452 $this->loadSkinModules( $sk );
2454 MWDebug
::addModules( $this );
2456 // Avoid PHP 7.1 warning of passing $this by reference
2457 $outputPage = $this;
2458 // Hook that allows last minute changes to the output page, e.g.
2459 // adding of CSS or Javascript by extensions.
2460 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2464 } catch ( Exception
$e ) {
2465 ob_end_clean(); // bug T129657
2471 // This hook allows last minute changes to final overall output by modifying output buffer
2472 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2473 } catch ( Exception
$e ) {
2474 ob_end_clean(); // bug T129657
2478 $this->sendCacheControl();
2481 return ob_get_clean();
2489 * Prepare this object to display an error page; disable caching and
2490 * indexing, clear the current text and redirect, set the page's title
2491 * and optionally an custom HTML title (content of the "<title>" tag).
2493 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2494 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2495 * optional, if not passed the "<title>" attribute will be
2496 * based on $pageTitle
2498 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2499 $this->setPageTitle( $pageTitle );
2500 if ( $htmlTitle !== false ) {
2501 $this->setHTMLTitle( $htmlTitle );
2503 $this->setRobotPolicy( 'noindex,nofollow' );
2504 $this->setArticleRelated( false );
2505 $this->enableClientCache( false );
2506 $this->mRedirect
= '';
2507 $this->clearSubtitle();
2512 * Output a standard error page
2514 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2515 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2516 * showErrorPage( 'titlemsg', $messageObject );
2517 * showErrorPage( $titleMessageObject, $messageObject );
2519 * @param string|Message $title Message key (string) for page title, or a Message object
2520 * @param string|Message $msg Message key (string) for page text, or a Message object
2521 * @param array $params Message parameters; ignored if $msg is a Message object
2523 public function showErrorPage( $title, $msg, $params = [] ) {
2524 if ( !$title instanceof Message
) {
2525 $title = $this->msg( $title );
2528 $this->prepareErrorPage( $title );
2530 if ( $msg instanceof Message
) {
2531 if ( $params !== [] ) {
2532 trigger_error( 'Argument ignored: $params. The message parameters argument '
2533 . 'is discarded when the $msg argument is a Message object instead of '
2534 . 'a string.', E_USER_NOTICE
);
2536 $this->addHTML( $msg->parseAsBlock() );
2538 $this->addWikiMsgArray( $msg, $params );
2541 $this->returnToMain();
2545 * Output a standard permission error page
2547 * @param array $errors Error message keys or [key, param...] arrays
2548 * @param string $action Action that was denied or null if unknown
2550 public function showPermissionsErrorPage( array $errors, $action = null ) {
2551 foreach ( $errors as $key => $error ) {
2552 $errors[$key] = (array)$error;
2555 // For some action (read, edit, create and upload), display a "login to do this action"
2556 // error if all of the following conditions are met:
2557 // 1. the user is not logged in
2558 // 2. the only error is insufficient permissions (i.e. no block or something else)
2559 // 3. the error can be avoided simply by logging in
2560 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2561 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2562 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2563 && ( User
::groupHasPermission( 'user', $action )
2564 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2566 $displayReturnto = null;
2568 # Due to T34276, if a user does not have read permissions,
2569 # $this->getTitle() will just give Special:Badtitle, which is
2570 # not especially useful as a returnto parameter. Use the title
2571 # from the request instead, if there was one.
2572 $request = $this->getRequest();
2573 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2574 if ( $action == 'edit' ) {
2575 $msg = 'whitelistedittext';
2576 $displayReturnto = $returnto;
2577 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2578 $msg = 'nocreatetext';
2579 } elseif ( $action == 'upload' ) {
2580 $msg = 'uploadnologintext';
2582 $msg = 'loginreqpagetext';
2583 $displayReturnto = Title
::newMainPage();
2589 $query['returnto'] = $returnto->getPrefixedText();
2591 if ( !$request->wasPosted() ) {
2592 $returntoquery = $request->getValues();
2593 unset( $returntoquery['title'] );
2594 unset( $returntoquery['returnto'] );
2595 unset( $returntoquery['returntoquery'] );
2596 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2599 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2600 $loginLink = $linkRenderer->makeKnownLink(
2601 SpecialPage
::getTitleFor( 'Userlogin' ),
2602 $this->msg( 'loginreqlink' )->text(),
2607 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2608 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2610 # Don't return to a page the user can't read otherwise
2611 # we'll end up in a pointless loop
2612 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2613 $this->returnToMain( null, $displayReturnto );
2616 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2617 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2622 * Display an error page indicating that a given version of MediaWiki is
2623 * required to use it
2625 * @param mixed $version The version of MediaWiki needed to use the page
2627 public function versionRequired( $version ) {
2628 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2630 $this->addWikiMsg( 'versionrequiredtext', $version );
2631 $this->returnToMain();
2635 * Format a list of error messages
2637 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2638 * @param string $action Action that was denied or null if unknown
2639 * @return string The wikitext error-messages, formatted into a list.
2641 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2642 if ( $action == null ) {
2643 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2645 $action_desc = $this->msg( "action-$action" )->plain();
2647 'permissionserrorstext-withaction',
2650 )->plain() . "\n\n";
2653 if ( count( $errors ) > 1 ) {
2654 $text .= '<ul class="permissions-errors">' . "\n";
2656 foreach ( $errors as $error ) {
2658 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2663 $text .= "<div class=\"permissions-errors\">\n" .
2664 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2672 * Show a warning about replica DB lag
2674 * If the lag is higher than $wgSlaveLagCritical seconds,
2675 * then the warning is a bit more obvious. If the lag is
2676 * lower than $wgSlaveLagWarning, then no warning is shown.
2678 * @param int $lag Slave lag
2680 public function showLagWarning( $lag ) {
2681 $config = $this->getConfig();
2682 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2683 $lag = floor( $lag ); // floor to avoid nano seconds to display
2684 $message = $lag < $config->get( 'SlaveLagCritical' )
2687 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2688 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2692 public function showFatalError( $message ) {
2693 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2695 $this->addHTML( $message );
2698 public function showUnexpectedValueError( $name, $val ) {
2699 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2702 public function showFileCopyError( $old, $new ) {
2703 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2706 public function showFileRenameError( $old, $new ) {
2707 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2710 public function showFileDeleteError( $name ) {
2711 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2714 public function showFileNotFoundError( $name ) {
2715 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2719 * Add a "return to" link pointing to a specified title
2721 * @param Title $title Title to link
2722 * @param array $query Query string parameters
2723 * @param string $text Text of the link (input is not escaped)
2724 * @param array $options Options array to pass to Linker
2726 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2727 $linkRenderer = MediaWikiServices
::getInstance()
2728 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2729 $link = $this->msg( 'returnto' )->rawParams(
2730 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2731 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2735 * Add a "return to" link pointing to a specified title,
2736 * or the title indicated in the request, or else the main page
2738 * @param mixed $unused
2739 * @param Title|string $returnto Title or String to return to
2740 * @param string $returntoquery Query string for the return to link
2742 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2743 if ( $returnto == null ) {
2744 $returnto = $this->getRequest()->getText( 'returnto' );
2747 if ( $returntoquery == null ) {
2748 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2751 if ( $returnto === '' ) {
2752 $returnto = Title
::newMainPage();
2755 if ( is_object( $returnto ) ) {
2756 $titleObj = $returnto;
2758 $titleObj = Title
::newFromText( $returnto );
2760 // We don't want people to return to external interwiki. That
2761 // might potentially be used as part of a phishing scheme
2762 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2763 $titleObj = Title
::newMainPage();
2766 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2769 private function getRlClientContext() {
2770 if ( !$this->rlClientContext
) {
2771 $query = ResourceLoader
::makeLoaderQuery(
2772 [], // modules; not relevant
2773 $this->getLanguage()->getCode(),
2774 $this->getSkin()->getSkinName(),
2775 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2776 null, // version; not relevant
2777 ResourceLoader
::inDebugMode(),
2778 null, // only; not relevant
2779 $this->isPrintable(),
2780 $this->getRequest()->getBool( 'handheld' )
2782 $this->rlClientContext
= new ResourceLoaderContext(
2783 $this->getResourceLoader(),
2784 new FauxRequest( $query )
2786 if ( $this->contentOverrideCallbacks
) {
2787 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2788 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2789 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2790 $content = call_user_func( $callback, $title );
2791 if ( $content !== null ) {
2799 return $this->rlClientContext
;
2803 * Call this to freeze the module queue and JS config and create a formatter.
2805 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2806 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2807 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2808 * the module filters retroactively. Skins and extension hooks may also add modules until very
2809 * late in the request lifecycle.
2811 * @return ResourceLoaderClientHtml
2813 public function getRlClient() {
2814 if ( !$this->rlClient
) {
2815 $context = $this->getRlClientContext();
2816 $rl = $this->getResourceLoader();
2817 $this->addModules( [
2822 $this->addModuleStyles( [
2827 $this->getSkin()->setupSkinUserCss( $this );
2829 // Prepare exempt modules for buildExemptModules()
2830 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2832 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2834 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2835 // Separate user-specific batch for improved cache-hit ratio.
2836 $userBatch = [ 'user.styles', 'user' ];
2837 $siteBatch = array_diff( $moduleStyles, $userBatch );
2838 $dbr = wfGetDB( DB_REPLICA
);
2839 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2840 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2842 // Filter out modules handled by buildExemptModules()
2843 $moduleStyles = array_filter( $moduleStyles,
2844 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2845 $module = $rl->getModule( $name );
2847 $group = $module->getGroup();
2848 if ( isset( $exemptGroups[$group] ) ) {
2849 $exemptStates[$name] = 'ready';
2850 if ( !$module->isKnownEmpty( $context ) ) {
2851 // E.g. Don't output empty <styles>
2852 $exemptGroups[$group][] = $name;
2860 $this->rlExemptStyleModules
= $exemptGroups;
2862 $rlClient = new ResourceLoaderClientHtml( $context, [
2863 'target' => $this->getTarget(),
2864 'nonce' => $this->getCSPNonce(),
2866 $rlClient->setConfig( $this->getJSVars() );
2867 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2868 $rlClient->setModuleStyles( $moduleStyles );
2869 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2870 $rlClient->setExemptStates( $exemptStates );
2871 $this->rlClient
= $rlClient;
2873 return $this->rlClient
;
2877 * @param Skin $sk The given Skin
2878 * @param bool $includeStyle Unused
2879 * @return string The doctype, opening "<html>", and head element.
2881 public function headElement( Skin
$sk, $includeStyle = true ) {
2884 $userdir = $this->getLanguage()->getDir();
2885 $sitedir = $wgContLang->getDir();
2888 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2889 $this->getRlClient()->getDocumentAttributes(),
2890 $sk->getHtmlElementAttributes()
2892 $pieces[] = Html
::openElement( 'head' );
2894 if ( $this->getHTMLTitle() == '' ) {
2895 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2898 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2899 // Add <meta charset="UTF-8">
2900 // This should be before <title> since it defines the charset used by
2901 // text including the text inside <title>.
2902 // The spec recommends defining XHTML5's charset using the XML declaration
2904 // Our XML declaration is output by Html::htmlHeader.
2905 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2906 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2907 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2910 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2911 $pieces[] = $this->getRlClient()->getHeadHtml();
2912 $pieces[] = $this->buildExemptModules();
2913 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2914 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2916 // Use an IE conditional comment to serve the script only to old IE
2917 $pieces[] = '<!--[if lt IE 9]>' .
2918 ResourceLoaderClientHtml
::makeLoad(
2919 ResourceLoaderContext
::newDummyContext(),
2921 ResourceLoaderModule
::TYPE_SCRIPTS
,
2923 $this->getCSPNonce()
2927 $pieces[] = Html
::closeElement( 'head' );
2929 $bodyClasses = $this->mAdditionalBodyClasses
;
2930 $bodyClasses[] = 'mediawiki';
2932 # Classes for LTR/RTL directionality support
2933 $bodyClasses[] = $userdir;
2934 $bodyClasses[] = "sitedir-$sitedir";
2936 $underline = $this->getUser()->getOption( 'underline' );
2937 if ( $underline < 2 ) {
2938 // The following classes can be used here:
2939 // * mw-underline-always
2940 // * mw-underline-never
2941 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2944 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2945 # A <body> class is probably not the best way to do this . . .
2946 $bodyClasses[] = 'capitalize-all-nouns';
2949 // Parser feature migration class
2950 // The idea is that this will eventually be removed, after the wikitext
2951 // which requires it is cleaned up.
2952 $bodyClasses[] = 'mw-hide-empty-elt';
2954 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2955 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2957 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2960 // While the implode() is not strictly needed, it's used for backwards compatibility
2961 // (this used to be built as a string and hooks likely still expect that).
2962 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2964 // Allow skins and extensions to add body attributes they need
2965 $sk->addToBodyAttributes( $this, $bodyAttrs );
2966 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2968 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2970 return self
::combineWrappedStrings( $pieces );
2974 * Get a ResourceLoader object associated with this OutputPage
2976 * @return ResourceLoader
2978 public function getResourceLoader() {
2979 if ( is_null( $this->mResourceLoader
) ) {
2980 $this->mResourceLoader
= new ResourceLoader(
2982 LoggerFactory
::getInstance( 'resourceloader' )
2985 return $this->mResourceLoader
;
2989 * Explicily load or embed modules on a page.
2991 * @param array|string $modules One or more module names
2992 * @param string $only ResourceLoaderModule TYPE_ class constant
2993 * @param array $extraQuery [optional] Array with extra query parameters for the request
2994 * @return string|WrappedStringList HTML
2996 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2997 // Apply 'target' and 'origin' filters
2998 $modules = $this->filterModules( (array)$modules, null, $only );
3000 return ResourceLoaderClientHtml
::makeLoad(
3001 $this->getRlClientContext(),
3005 $this->getCSPNonce()
3010 * Combine WrappedString chunks and filter out empty ones
3012 * @param array $chunks
3013 * @return string|WrappedStringList HTML
3015 protected static function combineWrappedStrings( array $chunks ) {
3016 // Filter out empty values
3017 $chunks = array_filter( $chunks, 'strlen' );
3018 return WrappedString
::join( "\n", $chunks );
3022 * JS stuff to put at the bottom of the `<body>`.
3023 * These are legacy scripts ($this->mScripts), and user JS.
3025 * @return string|WrappedStringList HTML
3027 public function getBottomScripts() {
3029 $chunks[] = $this->getRlClient()->getBodyHtml();
3031 // Legacy non-ResourceLoader scripts
3032 $chunks[] = $this->mScripts
;
3034 if ( $this->limitReportJSData
) {
3035 $chunks[] = ResourceLoader
::makeInlineScript(
3036 ResourceLoader
::makeConfigSetScript(
3037 [ 'wgPageParseReport' => $this->limitReportJSData
]
3039 $this->getCSPNonce()
3043 return self
::combineWrappedStrings( $chunks );
3047 * Get the javascript config vars to include on this page
3049 * @return array Array of javascript config vars
3052 public function getJsConfigVars() {
3053 return $this->mJsConfigVars
;
3057 * Add one or more variables to be set in mw.config in JavaScript
3059 * @param string|array $keys Key or array of key/value pairs
3060 * @param mixed $value [optional] Value of the configuration variable
3062 public function addJsConfigVars( $keys, $value = null ) {
3063 if ( is_array( $keys ) ) {
3064 foreach ( $keys as $key => $value ) {
3065 $this->mJsConfigVars
[$key] = $value;
3070 $this->mJsConfigVars
[$keys] = $value;
3074 * Get an array containing the variables to be set in mw.config in JavaScript.
3076 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3077 * - in other words, page-independent/site-wide variables (without state).
3078 * You will only be adding bloat to the html page and causing page caches to
3079 * have to be purged on configuration changes.
3082 public function getJSVars() {
3087 $canonicalSpecialPageName = false; # T23115
3089 $title = $this->getTitle();
3090 $ns = $title->getNamespace();
3091 $canonicalNamespace = MWNamespace
::exists( $ns )
3092 ? MWNamespace
::getCanonicalName( $ns )
3093 : $title->getNsText();
3095 $sk = $this->getSkin();
3096 // Get the relevant title so that AJAX features can use the correct page name
3097 // when making API requests from certain special pages (T36972).
3098 $relevantTitle = $sk->getRelevantTitle();
3099 $relevantUser = $sk->getRelevantUser();
3101 if ( $ns == NS_SPECIAL
) {
3102 list( $canonicalSpecialPageName, /*...*/ ) =
3103 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3104 } elseif ( $this->canUseWikiPage() ) {
3105 $wikiPage = $this->getWikiPage();
3106 $curRevisionId = $wikiPage->getLatest();
3107 $articleId = $wikiPage->getId();
3110 $lang = $title->getPageViewLanguage();
3112 // Pre-process information
3113 $separatorTransTable = $lang->separatorTransformTable();
3114 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3115 $compactSeparatorTransTable = [
3116 implode( "\t", array_keys( $separatorTransTable ) ),
3117 implode( "\t", $separatorTransTable ),
3119 $digitTransTable = $lang->digitTransformTable();
3120 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3121 $compactDigitTransTable = [
3122 implode( "\t", array_keys( $digitTransTable ) ),
3123 implode( "\t", $digitTransTable ),
3126 $user = $this->getUser();
3129 'wgCanonicalNamespace' => $canonicalNamespace,
3130 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3131 'wgNamespaceNumber' => $title->getNamespace(),
3132 'wgPageName' => $title->getPrefixedDBkey(),
3133 'wgTitle' => $title->getText(),
3134 'wgCurRevisionId' => $curRevisionId,
3135 'wgRevisionId' => (int)$this->getRevisionId(),
3136 'wgArticleId' => $articleId,
3137 'wgIsArticle' => $this->isArticle(),
3138 'wgIsRedirect' => $title->isRedirect(),
3139 'wgAction' => Action
::getActionName( $this->getContext() ),
3140 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3141 'wgUserGroups' => $user->getEffectiveGroups(),
3142 'wgCategories' => $this->getCategories(),
3143 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3144 'wgPageContentLanguage' => $lang->getCode(),
3145 'wgPageContentModel' => $title->getContentModel(),
3146 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3147 'wgDigitTransformTable' => $compactDigitTransTable,
3148 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3149 'wgMonthNames' => $lang->getMonthNamesArray(),
3150 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3151 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3152 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3153 'wgRequestId' => WebRequest
::getRequestId(),
3156 if ( $user->isLoggedIn() ) {
3157 $vars['wgUserId'] = $user->getId();
3158 $vars['wgUserEditCount'] = $user->getEditCount();
3159 $userReg = $user->getRegistration();
3160 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3161 // Get the revision ID of the oldest new message on the user's talk
3162 // page. This can be used for constructing new message alerts on
3164 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3167 if ( $wgContLang->hasVariants() ) {
3168 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3170 // Same test as SkinTemplate
3171 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3172 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3174 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3175 && $relevantTitle->quickUserCan( 'edit', $user )
3176 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3178 foreach ( $title->getRestrictionTypes() as $type ) {
3179 // Following keys are set in $vars:
3180 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3181 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3184 if ( $title->isMainPage() ) {
3185 $vars['wgIsMainPage'] = true;
3188 if ( $this->mRedirectedFrom
) {
3189 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3192 if ( $relevantUser ) {
3193 $vars['wgRelevantUserName'] = $relevantUser->getName();
3196 // Allow extensions to add their custom variables to the mw.config map.
3197 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3198 // page-dependant but site-wide (without state).
3199 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3200 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3202 // Merge in variables from addJsConfigVars last
3203 return array_merge( $vars, $this->getJsConfigVars() );
3207 * To make it harder for someone to slip a user a fake
3208 * JavaScript or CSS preview, a random token
3209 * is associated with the login session. If it's not
3210 * passed back with the preview request, we won't render
3215 public function userCanPreview() {
3216 $request = $this->getRequest();
3218 $request->getVal( 'action' ) !== 'submit' ||
3219 !$request->wasPosted()
3224 $user = $this->getUser();
3226 if ( !$user->isLoggedIn() ) {
3227 // Anons have predictable edit tokens
3230 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3234 $title = $this->getTitle();
3235 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3236 if ( count( $errors ) !== 0 ) {
3244 * @return array Array in format "link name or number => 'link html'".
3246 public function getHeadLinksArray() {
3250 $config = $this->getConfig();
3252 $canonicalUrl = $this->mCanonicalUrl
;
3254 $tags['meta-generator'] = Html
::element( 'meta', [
3255 'name' => 'generator',
3256 'content' => "MediaWiki $wgVersion",
3259 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3260 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3261 // fallbacks should come before the primary value so we need to reverse the array.
3262 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3263 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3264 'name' => 'referrer',
3265 'content' => $policy,
3270 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3271 if ( $p !== 'index,follow' ) {
3272 // http://www.robotstxt.org/wc/meta-user.html
3273 // Only show if it's different from the default robots policy
3274 $tags['meta-robots'] = Html
::element( 'meta', [
3280 foreach ( $this->mMetatags
as $tag ) {
3281 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3283 $tag[0] = substr( $tag[0], 5 );
3284 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3289 $tagName = "meta-{$tag[0]}";
3290 if ( isset( $tags[$tagName] ) ) {
3291 $tagName .= $tag[1];
3293 $tags[$tagName] = Html
::element( 'meta',
3296 'content' => $tag[1]
3301 foreach ( $this->mLinktags
as $tag ) {
3302 $tags[] = Html
::element( 'link', $tag );
3305 # Universal edit button
3306 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3307 $user = $this->getUser();
3308 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3309 && ( $this->getTitle()->exists() ||
3310 $this->getTitle()->quickUserCan( 'create', $user ) )
3312 // Original UniversalEditButton
3313 $msg = $this->msg( 'edit' )->text();
3314 $tags['universal-edit-button'] = Html
::element( 'link', [
3315 'rel' => 'alternate',
3316 'type' => 'application/x-wiki',
3318 'href' => $this->getTitle()->getEditURL(),
3320 // Alternate edit link
3321 $tags['alternative-edit'] = Html
::element( 'link', [
3324 'href' => $this->getTitle()->getEditURL(),
3329 # Generally the order of the favicon and apple-touch-icon links
3330 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3331 # uses whichever one appears later in the HTML source. Make sure
3332 # apple-touch-icon is specified first to avoid this.
3333 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3334 $tags['apple-touch-icon'] = Html
::element( 'link', [
3335 'rel' => 'apple-touch-icon',
3336 'href' => $config->get( 'AppleTouchIcon' )
3340 if ( $config->get( 'Favicon' ) !== false ) {
3341 $tags['favicon'] = Html
::element( 'link', [
3342 'rel' => 'shortcut icon',
3343 'href' => $config->get( 'Favicon' )
3347 # OpenSearch description link
3348 $tags['opensearch'] = Html
::element( 'link', [
3350 'type' => 'application/opensearchdescription+xml',
3351 'href' => wfScript( 'opensearch_desc' ),
3352 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3355 # Real Simple Discovery link, provides auto-discovery information
3356 # for the MediaWiki API (and potentially additional custom API
3357 # support such as WordPress or Twitter-compatible APIs for a
3358 # blogging extension, etc)
3359 $tags['rsd'] = Html
::element( 'link', [
3361 'type' => 'application/rsd+xml',
3362 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3363 // Whether RSD accepts relative or protocol-relative URLs is completely
3364 // undocumented, though.
3365 'href' => wfExpandUrl( wfAppendQuery(
3367 [ 'action' => 'rsd' ] ),
3373 if ( !$config->get( 'DisableLangConversion' ) ) {
3374 $lang = $this->getTitle()->getPageLanguage();
3375 if ( $lang->hasVariants() ) {
3376 $variants = $lang->getVariants();
3377 foreach ( $variants as $variant ) {
3378 $tags["variant-$variant"] = Html
::element( 'link', [
3379 'rel' => 'alternate',
3380 'hreflang' => LanguageCode
::bcp47( $variant ),
3381 'href' => $this->getTitle()->getLocalURL(
3382 [ 'variant' => $variant ] )
3386 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3387 $tags["variant-x-default"] = Html
::element( 'link', [
3388 'rel' => 'alternate',
3389 'hreflang' => 'x-default',
3390 'href' => $this->getTitle()->getLocalURL() ] );
3395 if ( $this->copyrightUrl
!== null ) {
3396 $copyright = $this->copyrightUrl
;
3399 if ( $config->get( 'RightsPage' ) ) {
3400 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3403 $copyright = $copy->getLocalURL();
3407 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3408 $copyright = $config->get( 'RightsUrl' );
3413 $tags['copyright'] = Html
::element( 'link', [
3415 'href' => $copyright ]
3420 if ( $config->get( 'Feed' ) ) {
3423 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3424 # Use the page name for the title. In principle, this could
3425 # lead to issues with having the same name for different feeds
3426 # corresponding to the same page, but we can't avoid that at
3429 $feedLinks[] = $this->feedLink(
3432 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3434 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3439 # Recent changes feed should appear on every page (except recentchanges,
3440 # that would be redundant). Put it after the per-page feed to avoid
3441 # changing existing behavior. It's still available, probably via a
3442 # menu in your browser. Some sites might have a different feed they'd
3443 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3444 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3445 # If so, use it instead.
3446 $sitename = $config->get( 'Sitename' );
3447 if ( $config->get( 'OverrideSiteFeed' ) ) {
3448 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3449 // Note, this->feedLink escapes the url.
3450 $feedLinks[] = $this->feedLink(
3453 $this->msg( "site-{$type}-feed", $sitename )->text()
3456 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3457 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3458 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3459 $feedLinks[] = $this->feedLink(
3461 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3462 # For grep: 'site-rss-feed', 'site-atom-feed'
3463 $this->msg( "site-{$format}-feed", $sitename )->text()
3468 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3469 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3470 # use OutputPage::addFeedLink() instead.
3471 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3473 $tags +
= $feedLinks;
3477 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3478 if ( $canonicalUrl !== false ) {
3479 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3481 if ( $this->isArticleRelated() ) {
3482 // This affects all requests where "setArticleRelated" is true. This is
3483 // typically all requests that show content (query title, curid, oldid, diff),
3484 // and all wikipage actions (edit, delete, purge, info, history etc.).
3485 // It does not apply to File pages and Special pages.
3486 // 'history' and 'info' actions address page metadata rather than the page
3487 // content itself, so they may not be canonicalized to the view page url.
3488 // TODO: this ought to be better encapsulated in the Action class.
3489 $action = Action
::getActionName( $this->getContext() );
3490 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3491 $query = "action={$action}";
3495 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3497 $reqUrl = $this->getRequest()->getRequestURL();
3498 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3502 if ( $canonicalUrl !== false ) {
3503 $tags[] = Html
::element( 'link', [
3504 'rel' => 'canonical',
3505 'href' => $canonicalUrl
3513 * Generate a "<link rel/>" for a feed.
3515 * @param string $type Feed type
3516 * @param string $url URL to the feed
3517 * @param string $text Value of the "title" attribute
3518 * @return string HTML fragment
3520 private function feedLink( $type, $url, $text ) {
3521 return Html
::element( 'link', [
3522 'rel' => 'alternate',
3523 'type' => "application/$type+xml",
3530 * Add a local or specified stylesheet, with the given media options.
3531 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3533 * @param string $style URL to the file
3534 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3535 * @param string $condition For IE conditional comments, specifying an IE version
3536 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3538 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3541 $options['media'] = $media;
3544 $options['condition'] = $condition;
3547 $options['dir'] = $dir;
3549 $this->styles
[$style] = $options;
3553 * Adds inline CSS styles
3554 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3556 * @param mixed $style_css Inline CSS
3557 * @param string $flip Set to 'flip' to flip the CSS if needed
3559 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3560 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3561 # If wanted, and the interface is right-to-left, flip the CSS
3562 $style_css = CSSJanus
::transform( $style_css, true, false );
3564 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3568 * Build exempt modules and legacy non-ResourceLoader styles.
3570 * @return string|WrappedStringList HTML
3572 protected function buildExemptModules() {
3574 // Things that go after the ResourceLoaderDynamicStyles marker
3577 // We want site, private and user styles to override dynamically added styles from
3578 // general modules, but we want dynamically added styles to override statically added
3579 // style modules. So the order has to be:
3580 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3581 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3582 // - ResourceLoaderDynamicStyles marker
3583 // - site/private/user styles
3585 // Add legacy styles added through addStyle()/addInlineStyle() here
3586 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3588 $chunks[] = Html
::element(
3590 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3593 $separateReq = [ 'site.styles', 'user.styles' ];
3594 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3595 // Combinable modules
3596 $chunks[] = $this->makeResourceLoaderLink(
3597 array_diff( $moduleNames, $separateReq ),
3598 ResourceLoaderModule
::TYPE_STYLES
3601 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3602 // These require their own dedicated request in order to support "@import"
3603 // syntax, which is incompatible with concatenation. (T147667, T37562)
3604 $chunks[] = $this->makeResourceLoaderLink( $name,
3605 ResourceLoaderModule
::TYPE_STYLES
3610 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3616 public function buildCssLinksArray() {
3619 foreach ( $this->styles
as $file => $options ) {
3620 $link = $this->styleLink( $file, $options );
3622 $links[$file] = $link;
3629 * Generate \<link\> tags for stylesheets
3631 * @param string $style URL to the file
3632 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3633 * @return string HTML fragment
3635 protected function styleLink( $style, array $options ) {
3636 if ( isset( $options['dir'] ) ) {
3637 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3642 if ( isset( $options['media'] ) ) {
3643 $media = self
::transformCssMedia( $options['media'] );
3644 if ( is_null( $media ) ) {
3651 if ( substr( $style, 0, 1 ) == '/' ||
3652 substr( $style, 0, 5 ) == 'http:' ||
3653 substr( $style, 0, 6 ) == 'https:' ) {
3656 $config = $this->getConfig();
3657 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3658 $config->get( 'StyleVersion' );
3661 $link = Html
::linkedStyle( $url, $media );
3663 if ( isset( $options['condition'] ) ) {
3664 $condition = htmlspecialchars( $options['condition'] );
3665 $link = "<!--[if $condition]>$link<![endif]-->";
3671 * Transform path to web-accessible static resource.
3673 * This is used to add a validation hash as query string.
3674 * This aids various behaviors:
3676 * - Put long Cache-Control max-age headers on responses for improved
3677 * cache performance.
3678 * - Get the correct version of a file as expected by the current page.
3679 * - Instantly get the updated version of a file after deployment.
3681 * Avoid using this for urls included in HTML as otherwise clients may get different
3682 * versions of a resource when navigating the site depending on when the page was cached.
3683 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3684 * an external stylesheet).
3687 * @param Config $config
3688 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3689 * @return string URL
3691 public static function transformResourcePath( Config
$config, $path ) {
3695 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3696 if ( $remotePathPrefix === '' ) {
3697 // The configured base path is required to be empty string for
3698 // wikis in the domain root
3701 $remotePath = $remotePathPrefix;
3703 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3704 // - Path is outside wgResourceBasePath, ignore.
3705 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3708 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3709 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3710 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3711 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3712 $uploadPath = $config->get( 'UploadPath' );
3713 if ( strpos( $path, $uploadPath ) === 0 ) {
3714 $localDir = $config->get( 'UploadDirectory' );
3715 $remotePathPrefix = $remotePath = $uploadPath;
3718 $path = RelPath
::getRelativePath( $path, $remotePath );
3719 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3723 * Utility method for transformResourceFilePath().
3725 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3728 * @param string $remotePathPrefix URL path prefix that points to $localPath
3729 * @param string $localPath File directory exposed at $remotePath
3730 * @param string $file Path to target file relative to $localPath
3731 * @return string URL
3733 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3734 $hash = md5_file( "$localPath/$file" );
3735 if ( $hash === false ) {
3736 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3739 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3743 * Transform "media" attribute based on request parameters
3745 * @param string $media Current value of the "media" attribute
3746 * @return string Modified value of the "media" attribute, or null to skip
3749 public static function transformCssMedia( $media ) {
3752 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3753 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3755 // Switch in on-screen display for media testing
3757 'printable' => 'print',
3758 'handheld' => 'handheld',
3760 foreach ( $switches as $switch => $targetMedia ) {
3761 if ( $wgRequest->getBool( $switch ) ) {
3762 if ( $media == $targetMedia ) {
3764 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3765 /* This regex will not attempt to understand a comma-separated media_query_list
3767 * Example supported values for $media:
3768 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3769 * Example NOT supported value for $media:
3770 * '3d-glasses, screen, print and resolution > 90dpi'
3772 * If it's a print request, we never want any kind of screen stylesheets
3773 * If it's a handheld request (currently the only other choice with a switch),
3774 * we don't want simple 'screen' but we might want screen queries that
3775 * have a max-width or something, so we'll pass all others on and let the
3776 * client do the query.
3778 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3789 * Add a wikitext-formatted message to the output.
3790 * This is equivalent to:
3792 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3794 public function addWikiMsg( /*...*/ ) {
3795 $args = func_get_args();
3796 $name = array_shift( $args );
3797 $this->addWikiMsgArray( $name, $args );
3801 * Add a wikitext-formatted message to the output.
3802 * Like addWikiMsg() except the parameters are taken as an array
3803 * instead of a variable argument list.
3805 * @param string $name
3806 * @param array $args
3808 public function addWikiMsgArray( $name, $args ) {
3809 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3813 * This function takes a number of message/argument specifications, wraps them in
3814 * some overall structure, and then parses the result and adds it to the output.
3816 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3817 * and so on. The subsequent arguments may be either
3818 * 1) strings, in which case they are message names, or
3819 * 2) arrays, in which case, within each array, the first element is the message
3820 * name, and subsequent elements are the parameters to that message.
3822 * Don't use this for messages that are not in the user's interface language.
3826 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3830 * $wgOut->addWikiText( "<div class='error'>\n"
3831 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3833 * The newline after the opening div is needed in some wikitext. See T21226.
3835 * @param string $wrap
3837 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3838 $msgSpecs = func_get_args();
3839 array_shift( $msgSpecs );
3840 $msgSpecs = array_values( $msgSpecs );
3842 foreach ( $msgSpecs as $n => $spec ) {
3843 if ( is_array( $spec ) ) {
3845 $name = array_shift( $args );
3846 if ( isset( $args['options'] ) ) {
3847 unset( $args['options'] );
3849 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3857 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3859 $this->addWikiText( $s );
3863 * Whether the output has a table of contents
3867 public function isTOCEnabled() {
3868 return $this->mEnableTOC
;
3872 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3875 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3877 public function enableSectionEditLinks( $flag = true ) {
3878 wfDeprecated( __METHOD__
, '1.31' );
3884 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3886 public function sectionEditLinksEnabled() {
3887 wfDeprecated( __METHOD__
, '1.31' );
3892 * Helper function to setup the PHP implementation of OOUI to use in this request.
3895 * @param String $skinName The Skin name to determine the correct OOUI theme
3896 * @param String $dir Language direction
3898 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3899 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3900 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : $themes['default'];
3901 // For example, 'OOUI\WikimediaUITheme'.
3902 $themeClass = "OOUI\\{$theme}Theme";
3903 OOUI\Theme
::setSingleton( new $themeClass() );
3904 OOUI\Element
::setDefaultDir( $dir );
3908 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3909 * MediaWiki and this OutputPage instance.
3913 public function enableOOUI() {
3915 strtolower( $this->getSkin()->getSkinName() ),
3916 $this->getLanguage()->getDir()
3918 $this->addModuleStyles( [
3919 'oojs-ui-core.styles',
3920 'oojs-ui.styles.indicators',
3921 'oojs-ui.styles.textures',
3922 'mediawiki.widgets.styles',
3923 'oojs-ui.styles.icons-content',
3924 'oojs-ui.styles.icons-alerts',
3925 'oojs-ui.styles.icons-interactions',
3930 * Add Link headers for preloading the wiki's logo.
3934 protected function addLogoPreloadLinkHeaders() {
3935 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3941 if ( !is_array( $logo ) ) {
3942 // No media queries required if we only have one variant
3943 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3947 if ( isset( $logo['svg'] ) ) {
3948 // No media queries required if we only have a 1x and svg variant
3949 // because all preload-capable browsers support SVGs
3950 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3954 foreach ( $logo as $dppx => $src ) {
3955 // Keys are in this format: "1.5x"
3956 $dppx = substr( $dppx, 0, -1 );
3957 $logosPerDppx[$dppx] = $src;
3960 // Because PHP can't have floats as array keys
3961 uksort( $logosPerDppx, function ( $a , $b ) {
3962 $a = floatval( $a );
3963 $b = floatval( $b );
3968 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3969 return ( $a < $b ) ?
-1 : 1;
3972 foreach ( $logosPerDppx as $dppx => $src ) {
3973 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3976 $logosCount = count( $logos );
3977 // Logic must match ResourceLoaderSkinModule:
3978 // - 1x applies to resolution < 1.5dppx
3979 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3980 // - 2x applies to resolution >= 2dppx
3981 // Note that min-resolution and max-resolution are both inclusive.
3982 for ( $i = 0; $i < $logosCount; $i++
) {
3985 // min-resolution is ">=" (larger than or equal to)
3986 // "not min-resolution" is essentially "<"
3987 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3988 } elseif ( $i !== $logosCount - 1 ) {
3990 // Media query expressions can only apply "not" to the entire expression
3991 // (e.g. can't express ">= 1.5 and not >= 2).
3992 // Workaround: Use <= 1.9999 in place of < 2.
3993 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
3994 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3995 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
3998 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4001 $this->addLinkHeader(
4002 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
4008 * Get (and set if not yet set) the CSP nonce.
4010 * This value needs to be included in any <script> tags on the
4013 * @return string|bool Nonce or false to mean don't output nonce
4016 public function getCSPNonce() {
4017 if ( !ContentSecurityPolicy
::isEnabled( $this->getConfig() ) ) {
4020 if ( $this->CSPNonce
=== null ) {
4021 // XXX It might be expensive to generate randomness
4022 // on every request, on windows.
4023 $rand = MWCryptRand
::generate( 15 );
4024 $this->CSPNonce
= base64_encode( $rand );
4026 return $this->CSPNonce
;