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\Logger\LoggerFactory
;
24 use MediaWiki\Session\SessionManager
;
25 use WrappedString\WrappedString
;
26 use WrappedString\WrappedStringList
;
29 * This class should be covered by a general architecture document which does
30 * not exist as of January 2011. This is one of the Core classes and should
31 * be read at least once by any new developers.
33 * This class is used to prepare the final rendering. A skin is then
34 * applied to the output parameters (links, javascript, html, categories ...).
36 * @todo FIXME: Another class handles sending the whole page to the client.
38 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
43 class OutputPage
extends ContextSource
{
44 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
45 protected $mMetatags = [];
48 protected $mLinktags = [];
51 protected $mCanonicalUrl = false;
54 * @var array Additional stylesheets. Looks like this is for extensions.
55 * Might be replaced by ResourceLoader.
57 protected $mExtStyles = [];
60 * @var string Should be private - has getter and setter. Contains
62 public $mPagetitle = '';
65 * @var string Contains all of the "<body>" content. Should be private we
66 * got set/get accessors and the append() method.
68 public $mBodytext = '';
71 * Holds the debug lines that will be output as comments in page source if
72 * $wgDebugComments is enabled. See also $wgShowDebug.
73 * @deprecated since 1.20; use MWDebug class instead.
75 public $mDebugtext = '';
77 /** @var string Stores contents of "<title>" tag */
78 private $mHTMLtitle = '';
81 * @var bool Is the displayed content related to the source of the
82 * corresponding wiki article.
84 private $mIsarticle = false;
86 /** @var bool Stores "article flag" toggle. */
87 private $mIsArticleRelated = true;
90 * @var bool We have to set isPrintable(). Some pages should
91 * never be printed (ex: redirections).
93 private $mPrintable = false;
96 * @var array Contains the page subtitle. Special pages usually have some
97 * links here. Don't confuse with site subtitle added by skins.
99 private $mSubtitle = [];
102 public $mRedirect = '';
105 protected $mStatusCode;
108 * @var string Used for sending cache control.
109 * The whole caching system should probably be moved into its own class.
111 protected $mLastModified = '';
114 protected $mCategoryLinks = [];
117 protected $mCategories = [];
120 protected $mIndicators = [];
122 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
123 private $mLanguageLinks = [];
126 * Used for JavaScript (predates ResourceLoader)
127 * @todo We should split JS / CSS.
128 * mScripts content is inserted as is in "<head>" by Skin. This might
129 * contain either a link to a stylesheet or inline CSS.
131 private $mScripts = '';
133 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
134 protected $mInlineStyles = '';
137 * @var string Used by skin template.
138 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
140 public $mPageLinkTitle = '';
142 /** @var array Array of elements in "<head>". Parser might add its own headers! */
143 protected $mHeadItems = [];
146 protected $mModules = [];
149 protected $mModuleScripts = [];
152 protected $mModuleStyles = [];
154 /** @var ResourceLoader */
155 protected $mResourceLoader;
158 protected $mJsConfigVars = [];
161 protected $mTemplateIds = [];
164 protected $mImageTimeKeys = [];
167 public $mRedirectCode = '';
169 protected $mFeedLinksAppendQuery = null;
172 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
173 * @see ResourceLoaderModule::$origin
174 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
176 protected $mAllowedModules = [
177 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
180 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
181 protected $mDoNothing = false;
186 protected $mContainsNewMagic = 0;
189 * lazy initialised, use parserOptions()
192 protected $mParserOptions = null;
195 * Handles the Atom / RSS links.
196 * We probably only support Atom in 2011.
197 * @see $wgAdvertisedFeedTypes
199 private $mFeedLinks = [];
201 // Gwicke work on squid caching? Roughly from 2003.
202 protected $mEnableClientCache = true;
204 /** @var bool Flag if output should only contain the body of the article. */
205 private $mArticleBodyOnly = false;
208 protected $mNewSectionLink = false;
211 protected $mHideNewSectionLink = false;
214 * @var bool Comes from the parser. This was probably made to load CSS/JS
215 * only if we had "<gallery>". Used directly in CategoryPage.php.
216 * Looks like ResourceLoader can replace this.
218 public $mNoGallery = false;
221 private $mPageTitleActionText = '';
223 /** @var int Cache stuff. Looks like mEnableClientCache */
224 protected $mCdnMaxage = 0;
225 /** @var int Upper limit on mCdnMaxage */
226 protected $mCdnMaxageLimit = INF
;
229 * @var bool Controls if anti-clickjacking / frame-breaking headers will
230 * be sent. This should be done for pages where edit actions are possible.
231 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
233 protected $mPreventClickjacking = true;
235 /** @var int To include the variable {{REVISIONID}} */
236 private $mRevisionId = null;
239 private $mRevisionTimestamp = null;
242 protected $mFileVersion = null;
245 * @var array An array of stylesheet filenames (relative from skins path),
246 * with options for CSS media, IE conditions, and RTL/LTR direction.
247 * For internal use; add settings in the skin via $this->addStyle()
249 * Style again! This seems like a code duplication since we already have
250 * mStyles. This is what makes Open Source amazing.
252 protected $styles = [];
254 private $mIndexPolicy = 'index';
255 private $mFollowPolicy = 'follow';
256 private $mVaryHeader = [
257 'Accept-Encoding' => [ 'match=gzip' ],
261 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
266 private $mRedirectedFrom = null;
269 * Additional key => value data
271 private $mProperties = [];
274 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
276 private $mTarget = null;
279 * @var bool Whether parser output should contain table of contents
281 private $mEnableTOC = true;
284 * @var bool Whether parser output should contain section edit links
286 private $mEnableSectionEditLinks = true;
289 * @var string|null The URL to send in a <link> element with rel=copyright
291 private $copyrightUrl;
294 * Constructor for OutputPage. This should not be called directly.
295 * Instead a new RequestContext should be created and it will implicitly create
296 * a OutputPage tied to that context.
297 * @param IContextSource|null $context
299 function __construct( IContextSource
$context = null ) {
300 if ( $context === null ) {
301 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
302 wfDeprecated( __METHOD__
, '1.18' );
304 $this->setContext( $context );
309 * Redirect to $url rather than displaying the normal page
311 * @param string $url URL
312 * @param string $responsecode HTTP status code
314 public function redirect( $url, $responsecode = '302' ) {
315 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
316 $this->mRedirect
= str_replace( "\n", '', $url );
317 $this->mRedirectCode
= $responsecode;
321 * Get the URL to redirect to, or an empty string if not redirect URL set
325 public function getRedirect() {
326 return $this->mRedirect
;
330 * Set the copyright URL to send with the output.
331 * Empty string to omit, null to reset.
335 * @param string|null $url
337 public function setCopyrightUrl( $url ) {
338 $this->copyrightUrl
= $url;
342 * Set the HTTP status code to send with the output.
344 * @param int $statusCode
346 public function setStatusCode( $statusCode ) {
347 $this->mStatusCode
= $statusCode;
351 * Add a new "<meta>" tag
352 * To add an http-equiv meta tag, precede the name with "http:"
354 * @param string $name Tag name
355 * @param string $val Tag value
357 function addMeta( $name, $val ) {
358 array_push( $this->mMetatags
, [ $name, $val ] );
362 * Returns the current <meta> tags
367 public function getMetaTags() {
368 return $this->mMetatags
;
372 * Add a new \<link\> tag to the page header.
374 * Note: use setCanonicalUrl() for rel=canonical.
376 * @param array $linkarr Associative array of attributes.
378 function addLink( array $linkarr ) {
379 array_push( $this->mLinktags
, $linkarr );
383 * Returns the current <link> tags
388 public function getLinkTags() {
389 return $this->mLinktags
;
393 * Add a new \<link\> with "rel" attribute set to "meta"
395 * @param array $linkarr Associative array mapping attribute names to their
396 * values, both keys and values will be escaped, and the
397 * "rel" attribute will be automatically added
399 function addMetadataLink( array $linkarr ) {
400 $linkarr['rel'] = $this->getMetadataAttribute();
401 $this->addLink( $linkarr );
405 * Set the URL to be used for the <link rel=canonical>. This should be used
406 * in preference to addLink(), to avoid duplicate link tags.
409 function setCanonicalUrl( $url ) {
410 $this->mCanonicalUrl
= $url;
414 * Returns the URL to be used for the <link rel=canonical> if
418 * @return bool|string
420 public function getCanonicalUrl() {
421 return $this->mCanonicalUrl
;
425 * Get the value of the "rel" attribute for metadata links
429 public function getMetadataAttribute() {
430 # note: buggy CC software only reads first "meta" link
431 static $haveMeta = false;
433 return 'alternate meta';
441 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
442 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
445 * @param string $script Raw HTML
447 function addScript( $script ) {
448 $this->mScripts
.= $script;
452 * Register and add a stylesheet from an extension directory.
454 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
455 * @param string $url Path to sheet. Provide either a full url (beginning
456 * with 'http', etc) or a relative path from the document root
457 * (beginning with '/'). Otherwise it behaves identically to
458 * addStyle() and draws from the /skins folder.
460 public function addExtensionStyle( $url ) {
461 wfDeprecated( __METHOD__
, '1.27' );
462 array_push( $this->mExtStyles
, $url );
466 * Get all styles added by extensions
468 * @deprecated since 1.27
471 function getExtStyle() {
472 wfDeprecated( __METHOD__
, '1.27' );
473 return $this->mExtStyles
;
477 * Add a JavaScript file out of skins/common, or a given relative path.
478 * Internal use only. Use OutputPage::addModules() if possible.
480 * @param string $file Filename in skins/common or complete on-server path
482 * @param string $version Style version of the file. Defaults to $wgStyleVersion
484 public function addScriptFile( $file, $version = null ) {
485 // See if $file parameter is an absolute URL or begins with a slash
486 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
489 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
491 if ( is_null( $version ) ) {
492 $version = $this->getConfig()->get( 'StyleVersion' );
494 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
498 * Add a self-contained script tag with the given contents
499 * Internal use only. Use OutputPage::addModules() if possible.
501 * @param string $script JavaScript text, no "<script>" tags
503 public function addInlineScript( $script ) {
504 $this->mScripts
.= Html
::inlineScript( $script );
508 * Filter an array of modules to remove insufficiently trustworthy members, and modules
509 * which are no longer registered (eg a page is cached before an extension is disabled)
510 * @param array $modules
511 * @param string|null $position If not null, only return modules with this position
512 * @param string $type
515 protected function filterModules( array $modules, $position = null,
516 $type = ResourceLoaderModule
::TYPE_COMBINED
518 $resourceLoader = $this->getResourceLoader();
519 $filteredModules = [];
520 foreach ( $modules as $val ) {
521 $module = $resourceLoader->getModule( $val );
522 if ( $module instanceof ResourceLoaderModule
523 && $module->getOrigin() <= $this->getAllowedModules( $type )
524 && ( is_null( $position ) ||
$module->getPosition() == $position )
525 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
527 $filteredModules[] = $val;
530 return $filteredModules;
534 * Get the list of modules to include on this page
536 * @param bool $filter Whether to filter out insufficiently trustworthy modules
537 * @param string|null $position If not null, only return modules with this position
538 * @param string $param
539 * @return array Array of module names
541 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
542 $modules = array_values( array_unique( $this->$param ) );
544 ?
$this->filterModules( $modules, $position )
549 * Add one or more modules recognized by ResourceLoader. Modules added
550 * through this function will be loaded by ResourceLoader when the
553 * @param string|array $modules Module name (string) or array of module names
555 public function addModules( $modules ) {
556 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
560 * Get the list of module JS to include on this page
562 * @param bool $filter
563 * @param string|null $position
565 * @return array Array of module names
567 public function getModuleScripts( $filter = false, $position = null ) {
568 return $this->getModules( $filter, $position, 'mModuleScripts' );
572 * Add only JS of one or more modules recognized by ResourceLoader. Module
573 * scripts added through this function will be loaded by ResourceLoader when
576 * @param string|array $modules Module name (string) or array of module names
578 public function addModuleScripts( $modules ) {
579 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
583 * Get the list of module CSS to include on this page
585 * @param bool $filter
586 * @param string|null $position
588 * @return array Array of module names
590 public function getModuleStyles( $filter = false, $position = null ) {
591 return $this->getModules( $filter, $position, 'mModuleStyles' );
595 * Add only CSS of one or more modules recognized by ResourceLoader.
597 * Module styles added through this function will be added using standard link CSS
598 * tags, rather than as a combined Javascript and CSS package. Thus, they will
599 * load when JavaScript is disabled (unless CSS also happens to be disabled).
601 * @param string|array $modules Module name (string) or array of module names
603 public function addModuleStyles( $modules ) {
604 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
608 * @return null|string ResourceLoader target
610 public function getTarget() {
611 return $this->mTarget
;
615 * Sets ResourceLoader target for load.php links. If null, will be omitted
617 * @param string|null $target
619 public function setTarget( $target ) {
620 $this->mTarget
= $target;
624 * Get an array of head items
628 function getHeadItemsArray() {
629 return $this->mHeadItems
;
633 * Add or replace an header item to the output
635 * Whenever possible, use more specific options like ResourceLoader modules,
636 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
637 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
638 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
639 * This would be your very LAST fallback.
641 * @param string $name Item name
642 * @param string $value Raw HTML
644 public function addHeadItem( $name, $value ) {
645 $this->mHeadItems
[$name] = $value;
649 * Check if the header item $name is already set
651 * @param string $name Item name
654 public function hasHeadItem( $name ) {
655 return isset( $this->mHeadItems
[$name] );
659 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
662 public function setETag( $tag ) {
666 * Set whether the output should only contain the body of the article,
667 * without any skin, sidebar, etc.
668 * Used e.g. when calling with "action=render".
670 * @param bool $only Whether to output only the body of the article
672 public function setArticleBodyOnly( $only ) {
673 $this->mArticleBodyOnly
= $only;
677 * Return whether the output will contain only the body of the article
681 public function getArticleBodyOnly() {
682 return $this->mArticleBodyOnly
;
686 * Set an additional output property
689 * @param string $name
690 * @param mixed $value
692 public function setProperty( $name, $value ) {
693 $this->mProperties
[$name] = $value;
697 * Get an additional output property
700 * @param string $name
701 * @return mixed Property value or null if not found
703 public function getProperty( $name ) {
704 if ( isset( $this->mProperties
[$name] ) ) {
705 return $this->mProperties
[$name];
712 * checkLastModified tells the client to use the client-cached page if
713 * possible. If successful, the OutputPage is disabled so that
714 * any future call to OutputPage->output() have no effect.
716 * Side effect: sets mLastModified for Last-Modified header
718 * @param string $timestamp
720 * @return bool True if cache-ok headers was sent.
722 public function checkLastModified( $timestamp ) {
723 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
724 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
727 $config = $this->getConfig();
728 if ( !$config->get( 'CachePages' ) ) {
729 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
733 $timestamp = wfTimestamp( TS_MW
, $timestamp );
735 'page' => $timestamp,
736 'user' => $this->getUser()->getTouched(),
737 'epoch' => $config->get( 'CacheEpoch' )
739 if ( $config->get( 'UseSquid' ) ) {
740 // bug 44570: the core page itself may not change, but resources might
741 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
743 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
745 $maxModified = max( $modifiedTimes );
746 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
748 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
749 if ( $clientHeader === false ) {
750 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
754 # IE sends sizes after the date like this:
755 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
756 # this breaks strtotime().
757 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
759 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
760 $clientHeaderTime = strtotime( $clientHeader );
761 MediaWiki\restoreWarnings
();
762 if ( !$clientHeaderTime ) {
764 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
767 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
771 foreach ( $modifiedTimes as $name => $value ) {
772 if ( $info !== '' ) {
775 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
778 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
779 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
780 wfDebug( __METHOD__
. ": effective Last-Modified: " .
781 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
782 if ( $clientHeaderTime < $maxModified ) {
783 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
788 # Give a 304 Not Modified response code and disable body output
789 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
790 ini_set( 'zlib.output_compression', 0 );
791 $this->getRequest()->response()->statusHeader( 304 );
792 $this->sendCacheControl();
795 // Don't output a compressed blob when using ob_gzhandler;
796 // it's technically against HTTP spec and seems to confuse
797 // Firefox when the response gets split over two packets.
798 wfClearOutputBuffers();
804 * Override the last modified timestamp
806 * @param string $timestamp New timestamp, in a format readable by
809 public function setLastModified( $timestamp ) {
810 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
814 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
816 * @param string $policy The literal string to output as the contents of
817 * the meta tag. Will be parsed according to the spec and output in
821 public function setRobotPolicy( $policy ) {
822 $policy = Article
::formatRobotPolicy( $policy );
824 if ( isset( $policy['index'] ) ) {
825 $this->setIndexPolicy( $policy['index'] );
827 if ( isset( $policy['follow'] ) ) {
828 $this->setFollowPolicy( $policy['follow'] );
833 * Set the index policy for the page, but leave the follow policy un-
836 * @param string $policy Either 'index' or 'noindex'.
839 public function setIndexPolicy( $policy ) {
840 $policy = trim( $policy );
841 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
842 $this->mIndexPolicy
= $policy;
847 * Set the follow policy for the page, but leave the index policy un-
850 * @param string $policy Either 'follow' or 'nofollow'.
853 public function setFollowPolicy( $policy ) {
854 $policy = trim( $policy );
855 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
856 $this->mFollowPolicy
= $policy;
861 * Set the new value of the "action text", this will be added to the
862 * "HTML title", separated from it with " - ".
864 * @param string $text New value of the "action text"
866 public function setPageTitleActionText( $text ) {
867 $this->mPageTitleActionText
= $text;
871 * Get the value of the "action text"
875 public function getPageTitleActionText() {
876 return $this->mPageTitleActionText
;
880 * "HTML title" means the contents of "<title>".
881 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
883 * @param string|Message $name
885 public function setHTMLTitle( $name ) {
886 if ( $name instanceof Message
) {
887 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
889 $this->mHTMLtitle
= $name;
894 * Return the "HTML title", i.e. the content of the "<title>" tag.
898 public function getHTMLTitle() {
899 return $this->mHTMLtitle
;
903 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
907 public function setRedirectedFrom( $t ) {
908 $this->mRedirectedFrom
= $t;
912 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
913 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
914 * but not bad tags like \<script\>. This function automatically sets
915 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
916 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
917 * good tags like \<i\> will be dropped entirely.
919 * @param string|Message $name
921 public function setPageTitle( $name ) {
922 if ( $name instanceof Message
) {
923 $name = $name->setContext( $this->getContext() )->text();
926 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
927 # but leave "<i>foobar</i>" alone
928 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
929 $this->mPagetitle
= $nameWithTags;
931 # change "<i>foo&bar</i>" to "foo&bar"
933 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
934 ->inContentLanguage()
939 * Return the "page title", i.e. the content of the \<h1\> tag.
943 public function getPageTitle() {
944 return $this->mPagetitle
;
948 * Set the Title object to use
952 public function setTitle( Title
$t ) {
953 $this->getContext()->setTitle( $t );
957 * Replace the subtitle with $str
959 * @param string|Message $str New value of the subtitle. String should be safe HTML.
961 public function setSubtitle( $str ) {
962 $this->clearSubtitle();
963 $this->addSubtitle( $str );
967 * Add $str to the subtitle
969 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
971 public function addSubtitle( $str ) {
972 if ( $str instanceof Message
) {
973 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
975 $this->mSubtitle
[] = $str;
980 * Build message object for a subtitle containing a backlink to a page
982 * @param Title $title Title to link to
983 * @param array $query Array of additional parameters to include in the link
987 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
988 if ( $title->isRedirect() ) {
989 $query['redirect'] = 'no';
991 return wfMessage( 'backlinksubtitle' )
992 ->rawParams( Linker
::link( $title, null, [], $query ) );
996 * Add a subtitle containing a backlink to a page
998 * @param Title $title Title to link to
999 * @param array $query Array of additional parameters to include in the link
1001 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1002 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1006 * Clear the subtitles
1008 public function clearSubtitle() {
1009 $this->mSubtitle
= [];
1017 public function getSubtitle() {
1018 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1022 * Set the page as printable, i.e. it'll be displayed with all
1023 * print styles included
1025 public function setPrintable() {
1026 $this->mPrintable
= true;
1030 * Return whether the page is "printable"
1034 public function isPrintable() {
1035 return $this->mPrintable
;
1039 * Disable output completely, i.e. calling output() will have no effect
1041 public function disable() {
1042 $this->mDoNothing
= true;
1046 * Return whether the output will be completely disabled
1050 public function isDisabled() {
1051 return $this->mDoNothing
;
1055 * Show an "add new section" link?
1059 public function showNewSectionLink() {
1060 return $this->mNewSectionLink
;
1064 * Forcibly hide the new section link?
1068 public function forceHideNewSectionLink() {
1069 return $this->mHideNewSectionLink
;
1073 * Add or remove feed links in the page header
1074 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1075 * for the new version
1076 * @see addFeedLink()
1078 * @param bool $show True: add default feeds, false: remove all feeds
1080 public function setSyndicated( $show = true ) {
1082 $this->setFeedAppendQuery( false );
1084 $this->mFeedLinks
= [];
1089 * Add default feeds to the page header
1090 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1091 * for the new version
1092 * @see addFeedLink()
1094 * @param string $val Query to append to feed links or false to output
1097 public function setFeedAppendQuery( $val ) {
1098 $this->mFeedLinks
= [];
1100 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1101 $query = "feed=$type";
1102 if ( is_string( $val ) ) {
1103 $query .= '&' . $val;
1105 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1110 * Add a feed link to the page header
1112 * @param string $format Feed type, should be a key of $wgFeedClasses
1113 * @param string $href URL
1115 public function addFeedLink( $format, $href ) {
1116 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1117 $this->mFeedLinks
[$format] = $href;
1122 * Should we output feed links for this page?
1125 public function isSyndicated() {
1126 return count( $this->mFeedLinks
) > 0;
1130 * Return URLs for each supported syndication format for this page.
1131 * @return array Associating format keys with URLs
1133 public function getSyndicationLinks() {
1134 return $this->mFeedLinks
;
1138 * Will currently always return null
1142 public function getFeedAppendQuery() {
1143 return $this->mFeedLinksAppendQuery
;
1147 * Set whether the displayed content is related to the source of the
1148 * corresponding article on the wiki
1149 * Setting true will cause the change "article related" toggle to true
1153 public function setArticleFlag( $v ) {
1154 $this->mIsarticle
= $v;
1156 $this->mIsArticleRelated
= $v;
1161 * Return whether the content displayed page is related to the source of
1162 * the corresponding article on the wiki
1166 public function isArticle() {
1167 return $this->mIsarticle
;
1171 * Set whether this page is related an article on the wiki
1172 * Setting false will cause the change of "article flag" toggle to false
1176 public function setArticleRelated( $v ) {
1177 $this->mIsArticleRelated
= $v;
1179 $this->mIsarticle
= false;
1184 * Return whether this page is related an article on the wiki
1188 public function isArticleRelated() {
1189 return $this->mIsArticleRelated
;
1193 * Add new language links
1195 * @param array $newLinkArray Associative array mapping language code to the page
1198 public function addLanguageLinks( array $newLinkArray ) {
1199 $this->mLanguageLinks +
= $newLinkArray;
1203 * Reset the language links and add new language links
1205 * @param array $newLinkArray Associative array mapping language code to the page
1208 public function setLanguageLinks( array $newLinkArray ) {
1209 $this->mLanguageLinks
= $newLinkArray;
1213 * Get the list of language links
1215 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1217 public function getLanguageLinks() {
1218 return $this->mLanguageLinks
;
1222 * Add an array of categories, with names in the keys
1224 * @param array $categories Mapping category name => sort key
1226 public function addCategoryLinks( array $categories ) {
1229 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1233 # Add the links to a LinkBatch
1234 $arr = [ NS_CATEGORY
=> $categories ];
1235 $lb = new LinkBatch
;
1236 $lb->setArray( $arr );
1238 # Fetch existence plus the hiddencat property
1239 $dbr = wfGetDB( DB_SLAVE
);
1240 $fields = array_merge(
1241 LinkCache
::getSelectFields(),
1242 [ 'page_namespace', 'page_title', 'pp_value' ]
1245 $res = $dbr->select( [ 'page', 'page_props' ],
1247 $lb->constructSet( 'page', $dbr ),
1250 [ 'page_props' => [ 'LEFT JOIN', [
1251 'pp_propname' => 'hiddencat',
1256 # Add the results to the link cache
1257 $lb->addResultToCache( LinkCache
::singleton(), $res );
1259 # Set all the values to 'normal'.
1260 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1262 # Mark hidden categories
1263 foreach ( $res as $row ) {
1264 if ( isset( $row->pp_value
) ) {
1265 $categories[$row->page_title
] = 'hidden';
1269 # Add the remaining categories to the skin
1271 'OutputPageMakeCategoryLinks',
1272 [ &$this, $categories, &$this->mCategoryLinks
] )
1274 foreach ( $categories as $category => $type ) {
1275 // array keys will cast numeric category names to ints, so cast back to string
1276 $category = (string)$category;
1277 $origcategory = $category;
1278 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1282 $wgContLang->findVariantLink( $category, $title, true );
1283 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1286 $text = $wgContLang->convertHtml( $title->getText() );
1287 $this->mCategories
[] = $title->getText();
1288 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1294 * Reset the category links (but not the category list) and add $categories
1296 * @param array $categories Mapping category name => sort key
1298 public function setCategoryLinks( array $categories ) {
1299 $this->mCategoryLinks
= [];
1300 $this->addCategoryLinks( $categories );
1304 * Get the list of category links, in a 2-D array with the following format:
1305 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1306 * hidden categories) and $link a HTML fragment with a link to the category
1311 public function getCategoryLinks() {
1312 return $this->mCategoryLinks
;
1316 * Get the list of category names this page belongs to
1318 * @return array Array of strings
1320 public function getCategories() {
1321 return $this->mCategories
;
1325 * Add an array of indicators, with their identifiers as array
1326 * keys and HTML contents as values.
1328 * In case of duplicate keys, existing values are overwritten.
1330 * @param array $indicators
1333 public function setIndicators( array $indicators ) {
1334 $this->mIndicators
= $indicators +
$this->mIndicators
;
1335 // Keep ordered by key
1336 ksort( $this->mIndicators
);
1340 * Get the indicators associated with this page.
1342 * The array will be internally ordered by item keys.
1344 * @return array Keys: identifiers, values: HTML contents
1347 public function getIndicators() {
1348 return $this->mIndicators
;
1352 * Adds help link with an icon via page indicators.
1353 * Link target can be overridden by a local message containing a wikilink:
1354 * the message key is: lowercase action or special page name + '-helppage'.
1355 * @param string $to Target MediaWiki.org page title or encoded URL.
1356 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1359 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1360 $this->addModuleStyles( 'mediawiki.helplink' );
1361 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1363 if ( $overrideBaseUrl ) {
1366 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1367 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1370 $link = Html
::rawElement(
1374 'target' => '_blank',
1375 'class' => 'mw-helplink',
1380 $this->setIndicators( [ 'mw-helplink' => $link ] );
1384 * Do not allow scripts which can be modified by wiki users to load on this page;
1385 * only allow scripts bundled with, or generated by, the software.
1386 * Site-wide styles are controlled by a config setting, since they can be
1387 * used to create a custom skin/theme, but not user-specific ones.
1389 * @todo this should be given a more accurate name
1391 public function disallowUserJs() {
1392 $this->reduceAllowedModules(
1393 ResourceLoaderModule
::TYPE_SCRIPTS
,
1394 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1397 // Site-wide styles are controlled by a config setting, see bug 71621
1398 // for background on why. User styles are never allowed.
1399 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1400 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1402 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1404 $this->reduceAllowedModules(
1405 ResourceLoaderModule
::TYPE_STYLES
,
1411 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1412 * @see ResourceLoaderModule::$origin
1413 * @param string $type ResourceLoaderModule TYPE_ constant
1414 * @return int ResourceLoaderModule ORIGIN_ class constant
1416 public function getAllowedModules( $type ) {
1417 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1418 return min( array_values( $this->mAllowedModules
) );
1420 return isset( $this->mAllowedModules
[$type] )
1421 ?
$this->mAllowedModules
[$type]
1422 : ResourceLoaderModule
::ORIGIN_ALL
;
1427 * Limit the highest level of CSS/JS untrustworthiness allowed.
1429 * If passed the same or a higher level than the current level of untrustworthiness set, the
1430 * level will remain unchanged.
1432 * @param string $type
1433 * @param int $level ResourceLoaderModule class constant
1435 public function reduceAllowedModules( $type, $level ) {
1436 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1440 * Prepend $text to the body HTML
1442 * @param string $text HTML
1444 public function prependHTML( $text ) {
1445 $this->mBodytext
= $text . $this->mBodytext
;
1449 * Append $text to the body HTML
1451 * @param string $text HTML
1453 public function addHTML( $text ) {
1454 $this->mBodytext
.= $text;
1458 * Shortcut for adding an Html::element via addHTML.
1462 * @param string $element
1463 * @param array $attribs
1464 * @param string $contents
1466 public function addElement( $element, array $attribs = [], $contents = '' ) {
1467 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1471 * Clear the body HTML
1473 public function clearHTML() {
1474 $this->mBodytext
= '';
1480 * @return string HTML
1482 public function getHTML() {
1483 return $this->mBodytext
;
1487 * Get/set the ParserOptions object to use for wikitext parsing
1489 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1490 * current ParserOption object
1491 * @return ParserOptions
1493 public function parserOptions( $options = null ) {
1494 if ( $options !== null && !empty( $options->isBogus
) ) {
1495 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1496 // been changed somehow, and keep it if so.
1497 $anonPO = ParserOptions
::newFromAnon();
1498 $anonPO->setEditSection( false );
1499 if ( !$options->matches( $anonPO ) ) {
1500 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1501 $options->isBogus
= false;
1505 if ( !$this->mParserOptions
) {
1506 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1507 // $wgUser isn't unstubbable yet, so don't try to get a
1508 // ParserOptions for it. And don't cache this ParserOptions
1510 $po = ParserOptions
::newFromAnon();
1511 $po->setEditSection( false );
1512 $po->isBogus
= true;
1513 if ( $options !== null ) {
1514 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1519 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1520 $this->mParserOptions
->setEditSection( false );
1523 if ( $options !== null && !empty( $options->isBogus
) ) {
1524 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1526 return wfSetVar( $this->mParserOptions
, null, true );
1528 return wfSetVar( $this->mParserOptions
, $options );
1533 * Set the revision ID which will be seen by the wiki text parser
1534 * for things such as embedded {{REVISIONID}} variable use.
1536 * @param int|null $revid An positive integer, or null
1537 * @return mixed Previous value
1539 public function setRevisionId( $revid ) {
1540 $val = is_null( $revid ) ?
null : intval( $revid );
1541 return wfSetVar( $this->mRevisionId
, $val );
1545 * Get the displayed revision ID
1549 public function getRevisionId() {
1550 return $this->mRevisionId
;
1554 * Set the timestamp of the revision which will be displayed. This is used
1555 * to avoid a extra DB call in Skin::lastModified().
1557 * @param string|null $timestamp
1558 * @return mixed Previous value
1560 public function setRevisionTimestamp( $timestamp ) {
1561 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1565 * Get the timestamp of displayed revision.
1566 * This will be null if not filled by setRevisionTimestamp().
1568 * @return string|null
1570 public function getRevisionTimestamp() {
1571 return $this->mRevisionTimestamp
;
1575 * Set the displayed file version
1577 * @param File|bool $file
1578 * @return mixed Previous value
1580 public function setFileVersion( $file ) {
1582 if ( $file instanceof File
&& $file->exists() ) {
1583 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1585 return wfSetVar( $this->mFileVersion
, $val, true );
1589 * Get the displayed file version
1591 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1593 public function getFileVersion() {
1594 return $this->mFileVersion
;
1598 * Get the templates used on this page
1600 * @return array (namespace => dbKey => revId)
1603 public function getTemplateIds() {
1604 return $this->mTemplateIds
;
1608 * Get the files used on this page
1610 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1613 public function getFileSearchOptions() {
1614 return $this->mImageTimeKeys
;
1618 * Convert wikitext to HTML and add it to the buffer
1619 * Default assumes that the current page title will be used.
1621 * @param string $text
1622 * @param bool $linestart Is this the start of a line?
1623 * @param bool $interface Is this text in the user interface language?
1624 * @throws MWException
1626 public function addWikiText( $text, $linestart = true, $interface = true ) {
1627 $title = $this->getTitle(); // Work around E_STRICT
1629 throw new MWException( 'Title is null' );
1631 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1635 * Add wikitext with a custom Title object
1637 * @param string $text Wikitext
1638 * @param Title $title
1639 * @param bool $linestart Is this the start of a line?
1641 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1642 $this->addWikiTextTitle( $text, $title, $linestart );
1646 * Add wikitext with a custom Title object and tidy enabled.
1648 * @param string $text Wikitext
1649 * @param Title $title
1650 * @param bool $linestart Is this the start of a line?
1652 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1653 $this->addWikiTextTitle( $text, $title, $linestart, true );
1657 * Add wikitext with tidy enabled
1659 * @param string $text Wikitext
1660 * @param bool $linestart Is this the start of a line?
1662 public function addWikiTextTidy( $text, $linestart = true ) {
1663 $title = $this->getTitle();
1664 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1668 * Add wikitext with a custom Title object
1670 * @param string $text Wikitext
1671 * @param Title $title
1672 * @param bool $linestart Is this the start of a line?
1673 * @param bool $tidy Whether to use tidy
1674 * @param bool $interface Whether it is an interface message
1675 * (for example disables conversion)
1677 public function addWikiTextTitle( $text, Title
$title, $linestart,
1678 $tidy = false, $interface = false
1682 $popts = $this->parserOptions();
1683 $oldTidy = $popts->setTidy( $tidy );
1684 $popts->setInterfaceMessage( (bool)$interface );
1686 $parserOutput = $wgParser->getFreshParser()->parse(
1687 $text, $title, $popts,
1688 $linestart, true, $this->mRevisionId
1691 $popts->setTidy( $oldTidy );
1693 $this->addParserOutput( $parserOutput );
1698 * Add a ParserOutput object, but without Html.
1700 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1701 * @param ParserOutput $parserOutput
1703 public function addParserOutputNoText( $parserOutput ) {
1704 wfDeprecated( __METHOD__
, '1.24' );
1705 $this->addParserOutputMetadata( $parserOutput );
1709 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1710 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1714 * @param ParserOutput $parserOutput
1716 public function addParserOutputMetadata( $parserOutput ) {
1717 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1718 $this->addCategoryLinks( $parserOutput->getCategories() );
1719 $this->setIndicators( $parserOutput->getIndicators() );
1720 $this->mNewSectionLink
= $parserOutput->getNewSection();
1721 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1723 if ( !$parserOutput->isCacheable() ) {
1724 $this->enableClientCache( false );
1726 $this->mNoGallery
= $parserOutput->getNoGallery();
1727 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1728 $this->addModules( $parserOutput->getModules() );
1729 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1730 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1731 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1732 $this->mPreventClickjacking
= $this->mPreventClickjacking
1733 ||
$parserOutput->preventClickjacking();
1735 // Template versioning...
1736 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1737 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1738 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1740 $this->mTemplateIds
[$ns] = $dbks;
1743 // File versioning...
1744 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1745 $this->mImageTimeKeys
[$dbk] = $data;
1748 // Hooks registered in the object
1749 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1750 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1751 list( $hookName, $data ) = $hookInfo;
1752 if ( isset( $parserOutputHooks[$hookName] ) ) {
1753 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1757 // enable OOUI if requested via ParserOutput
1758 if ( $parserOutput->getEnableOOUI() ) {
1759 $this->enableOOUI();
1762 // Link flags are ignored for now, but may in the future be
1763 // used to mark individual language links.
1765 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1766 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1770 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1771 * ParserOutput object, without any other metadata.
1774 * @param ParserOutput $parserOutput
1776 public function addParserOutputContent( $parserOutput ) {
1777 $this->addParserOutputText( $parserOutput );
1779 $this->addModules( $parserOutput->getModules() );
1780 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1781 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1783 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1787 * Add the HTML associated with a ParserOutput object, without any metadata.
1790 * @param ParserOutput $parserOutput
1792 public function addParserOutputText( $parserOutput ) {
1793 $text = $parserOutput->getText();
1794 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1795 $this->addHTML( $text );
1799 * Add everything from a ParserOutput object.
1801 * @param ParserOutput $parserOutput
1803 function addParserOutput( $parserOutput ) {
1804 $this->addParserOutputMetadata( $parserOutput );
1805 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1807 // Touch section edit links only if not previously disabled
1808 if ( $parserOutput->getEditSectionTokens() ) {
1809 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1812 $this->addParserOutputText( $parserOutput );
1816 * Add the output of a QuickTemplate to the output buffer
1818 * @param QuickTemplate $template
1820 public function addTemplate( &$template ) {
1821 $this->addHTML( $template->getHTML() );
1825 * Parse wikitext and return the HTML.
1827 * @param string $text
1828 * @param bool $linestart Is this the start of a line?
1829 * @param bool $interface Use interface language ($wgLang instead of
1830 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1831 * This also disables LanguageConverter.
1832 * @param Language $language Target language object, will override $interface
1833 * @throws MWException
1834 * @return string HTML
1836 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1839 if ( is_null( $this->getTitle() ) ) {
1840 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1843 $popts = $this->parserOptions();
1845 $popts->setInterfaceMessage( true );
1847 if ( $language !== null ) {
1848 $oldLang = $popts->setTargetLanguage( $language );
1851 $parserOutput = $wgParser->getFreshParser()->parse(
1852 $text, $this->getTitle(), $popts,
1853 $linestart, true, $this->mRevisionId
1857 $popts->setInterfaceMessage( false );
1859 if ( $language !== null ) {
1860 $popts->setTargetLanguage( $oldLang );
1863 return $parserOutput->getText();
1867 * Parse wikitext, strip paragraphs, and return the HTML.
1869 * @param string $text
1870 * @param bool $linestart Is this the start of a line?
1871 * @param bool $interface Use interface language ($wgLang instead of
1872 * $wgContLang) while parsing language sensitive magic
1873 * words like GRAMMAR and PLURAL
1874 * @return string HTML
1876 public function parseInline( $text, $linestart = true, $interface = false ) {
1877 $parsed = $this->parse( $text, $linestart, $interface );
1878 return Parser
::stripOuterParagraph( $parsed );
1883 * @deprecated since 1.27 Use setCdnMaxage() instead
1885 public function setSquidMaxage( $maxage ) {
1886 $this->setCdnMaxage( $maxage );
1890 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1892 * @param int $maxage Maximum cache time on the CDN, in seconds.
1894 public function setCdnMaxage( $maxage ) {
1895 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1899 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1901 * @param int $maxage Maximum cache time on the CDN, in seconds
1904 public function lowerCdnMaxage( $maxage ) {
1905 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1906 $this->setCdnMaxage( $this->mCdnMaxage
);
1910 * Use enableClientCache(false) to force it to send nocache headers
1912 * @param bool $state
1916 public function enableClientCache( $state ) {
1917 return wfSetVar( $this->mEnableClientCache
, $state );
1921 * Get the list of cookies that will influence on the cache
1925 function getCacheVaryCookies() {
1927 if ( $cookies === null ) {
1928 $config = $this->getConfig();
1929 $cookies = array_merge(
1930 SessionManager
::singleton()->getVaryCookies(),
1934 $config->get( 'CacheVaryCookies' )
1936 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
1942 * Check if the request has a cache-varying cookie header
1943 * If it does, it's very important that we don't allow public caching
1947 function haveCacheVaryCookies() {
1948 $request = $this->getRequest();
1949 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
1950 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
1951 wfDebug( __METHOD__
. ": found $cookieName\n" );
1955 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1960 * Add an HTTP header that will influence on the cache
1962 * @param string $header Header name
1963 * @param string[]|null $option Options for the Key header. See
1964 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
1965 * for the list of valid options.
1967 public function addVaryHeader( $header, array $option = null ) {
1968 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1969 $this->mVaryHeader
[$header] = [];
1971 if ( !is_array( $option ) ) {
1974 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
1978 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1979 * such as Accept-Encoding or Cookie
1983 public function getVaryHeader() {
1984 // If we vary on cookies, let's make sure it's always included here too.
1985 if ( $this->getCacheVaryCookies() ) {
1986 $this->addVaryHeader( 'Cookie' );
1989 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
1990 $this->addVaryHeader( $header, $options );
1992 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
1996 * Get a complete Key header
2000 public function getKeyHeader() {
2001 $cvCookies = $this->getCacheVaryCookies();
2003 $cookiesOption = [];
2004 foreach ( $cvCookies as $cookieName ) {
2005 $cookiesOption[] = 'param=' . $cookieName;
2007 $this->addVaryHeader( 'Cookie', $cookiesOption );
2009 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2010 $this->addVaryHeader( $header, $options );
2014 foreach ( $this->mVaryHeader
as $header => $option ) {
2015 $newheader = $header;
2016 if ( is_array( $option ) && count( $option ) > 0 ) {
2017 $newheader .= ';' . implode( ';', $option );
2019 $headers[] = $newheader;
2021 $key = 'Key: ' . implode( ',', $headers );
2027 * T23672: Add Accept-Language to Vary and Key headers
2028 * if there's no 'variant' parameter existed in GET.
2031 * /w/index.php?title=Main_page should always be served; but
2032 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2034 function addAcceptLanguage() {
2035 $title = $this->getTitle();
2036 if ( !$title instanceof Title
) {
2040 $lang = $title->getPageLanguage();
2041 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2042 $variants = $lang->getVariants();
2044 foreach ( $variants as $variant ) {
2045 if ( $variant === $lang->getCode() ) {
2048 $aloption[] = 'substr=' . $variant;
2050 // IE and some other browsers use BCP 47 standards in
2051 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2052 // We should handle these too.
2053 $variantBCP47 = wfBCP47( $variant );
2054 if ( $variantBCP47 !== $variant ) {
2055 $aloption[] = 'substr=' . $variantBCP47;
2059 $this->addVaryHeader( 'Accept-Language', $aloption );
2064 * Set a flag which will cause an X-Frame-Options header appropriate for
2065 * edit pages to be sent. The header value is controlled by
2066 * $wgEditPageFrameOptions.
2068 * This is the default for special pages. If you display a CSRF-protected
2069 * form on an ordinary view page, then you need to call this function.
2071 * @param bool $enable
2073 public function preventClickjacking( $enable = true ) {
2074 $this->mPreventClickjacking
= $enable;
2078 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2079 * This can be called from pages which do not contain any CSRF-protected
2082 public function allowClickjacking() {
2083 $this->mPreventClickjacking
= false;
2087 * Get the prevent-clickjacking flag
2092 public function getPreventClickjacking() {
2093 return $this->mPreventClickjacking
;
2097 * Get the X-Frame-Options header value (without the name part), or false
2098 * if there isn't one. This is used by Skin to determine whether to enable
2099 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2103 public function getFrameOptions() {
2104 $config = $this->getConfig();
2105 if ( $config->get( 'BreakFrames' ) ) {
2107 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2108 return $config->get( 'EditPageFrameOptions' );
2114 * Send cache control HTTP headers
2116 public function sendCacheControl() {
2117 $response = $this->getRequest()->response();
2118 $config = $this->getConfig();
2120 $this->addVaryHeader( 'Cookie' );
2121 $this->addAcceptLanguage();
2123 # don't serve compressed data to clients who can't handle it
2124 # maintain different caches for logged-in users and non-logged in ones
2125 $response->header( $this->getVaryHeader() );
2127 if ( $config->get( 'UseKeyHeader' ) ) {
2128 $response->header( $this->getKeyHeader() );
2131 if ( $this->mEnableClientCache
) {
2133 $config->get( 'UseSquid' ) &&
2134 !$response->hasCookies() &&
2135 !SessionManager
::getGlobalSession()->isPersistent() &&
2136 !$this->isPrintable() &&
2137 $this->mCdnMaxage
!= 0 &&
2138 !$this->haveCacheVaryCookies()
2140 if ( $config->get( 'UseESI' ) ) {
2141 # We'll purge the proxy cache explicitly, but require end user agents
2142 # to revalidate against the proxy on each visit.
2143 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2144 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2145 # start with a shorter timeout for initial testing
2146 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2147 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2148 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2149 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2151 # We'll purge the proxy cache for anons explicitly, but require end user agents
2152 # to revalidate against the proxy on each visit.
2153 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2154 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2155 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2156 # start with a shorter timeout for initial testing
2157 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2158 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2159 . ', must-revalidate, max-age=0' );
2162 # We do want clients to cache if they can, but they *must* check for updates
2163 # on revisiting the page.
2164 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2165 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2166 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2168 if ( $this->mLastModified
) {
2169 $response->header( "Last-Modified: {$this->mLastModified}" );
2172 wfDebug( __METHOD__
. ": no caching **", 'private' );
2174 # In general, the absence of a last modified header should be enough to prevent
2175 # the client from using its cache. We send a few other things just to make sure.
2176 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2177 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2178 $response->header( 'Pragma: no-cache' );
2183 * Finally, all the text has been munged and accumulated into
2184 * the object, let's actually output it:
2186 public function output() {
2187 if ( $this->mDoNothing
) {
2191 $response = $this->getRequest()->response();
2192 $config = $this->getConfig();
2194 if ( $this->mRedirect
!= '' ) {
2195 # Standards require redirect URLs to be absolute
2196 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2198 $redirect = $this->mRedirect
;
2199 $code = $this->mRedirectCode
;
2201 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2202 if ( $code == '301' ||
$code == '303' ) {
2203 if ( !$config->get( 'DebugRedirects' ) ) {
2204 $response->statusHeader( $code );
2206 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2208 if ( $config->get( 'VaryOnXFP' ) ) {
2209 $this->addVaryHeader( 'X-Forwarded-Proto' );
2211 $this->sendCacheControl();
2213 $response->header( "Content-Type: text/html; charset=utf-8" );
2214 if ( $config->get( 'DebugRedirects' ) ) {
2215 $url = htmlspecialchars( $redirect );
2216 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2217 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2218 print "</body>\n</html>\n";
2220 $response->header( 'Location: ' . $redirect );
2225 } elseif ( $this->mStatusCode
) {
2226 $response->statusHeader( $this->mStatusCode
);
2229 # Buffer output; final headers may depend on later processing
2232 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2233 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2235 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2236 // jQuery etc. can work correctly.
2237 $response->header( 'X-UA-Compatible: IE=Edge' );
2239 // Prevent framing, if requested
2240 $frameOptions = $this->getFrameOptions();
2241 if ( $frameOptions ) {
2242 $response->header( "X-Frame-Options: $frameOptions" );
2245 if ( $this->mArticleBodyOnly
) {
2246 echo $this->mBodytext
;
2248 $sk = $this->getSkin();
2249 // add skin specific modules
2250 $modules = $sk->getDefaultModules();
2252 // Enforce various default modules for all skins
2254 // Keep this list as small as possible
2256 'mediawiki.page.startup',
2260 // Support for high-density display images if enabled
2261 if ( $config->get( 'ResponsiveImages' ) ) {
2262 $coreModules[] = 'mediawiki.hidpi';
2265 $this->addModules( $coreModules );
2266 foreach ( $modules as $group ) {
2267 $this->addModules( $group );
2269 MWDebug
::addModules( $this );
2271 // Hook that allows last minute changes to the output page, e.g.
2272 // adding of CSS or Javascript by extensions.
2273 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2277 } catch ( Exception
$e ) {
2278 ob_end_clean(); // bug T129657
2284 // This hook allows last minute changes to final overall output by modifying output buffer
2285 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2286 } catch ( Exception
$e ) {
2287 ob_end_clean(); // bug T129657
2291 $this->sendCacheControl();
2298 * Prepare this object to display an error page; disable caching and
2299 * indexing, clear the current text and redirect, set the page's title
2300 * and optionally an custom HTML title (content of the "<title>" tag).
2302 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2303 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2304 * optional, if not passed the "<title>" attribute will be
2305 * based on $pageTitle
2307 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2308 $this->setPageTitle( $pageTitle );
2309 if ( $htmlTitle !== false ) {
2310 $this->setHTMLTitle( $htmlTitle );
2312 $this->setRobotPolicy( 'noindex,nofollow' );
2313 $this->setArticleRelated( false );
2314 $this->enableClientCache( false );
2315 $this->mRedirect
= '';
2316 $this->clearSubtitle();
2321 * Output a standard error page
2323 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2324 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2325 * showErrorPage( 'titlemsg', $messageObject );
2326 * showErrorPage( $titleMessageObject, $messageObject );
2328 * @param string|Message $title Message key (string) for page title, or a Message object
2329 * @param string|Message $msg Message key (string) for page text, or a Message object
2330 * @param array $params Message parameters; ignored if $msg is a Message object
2332 public function showErrorPage( $title, $msg, $params = [] ) {
2333 if ( !$title instanceof Message
) {
2334 $title = $this->msg( $title );
2337 $this->prepareErrorPage( $title );
2339 if ( $msg instanceof Message
) {
2340 if ( $params !== [] ) {
2341 trigger_error( 'Argument ignored: $params. The message parameters argument '
2342 . 'is discarded when the $msg argument is a Message object instead of '
2343 . 'a string.', E_USER_NOTICE
);
2345 $this->addHTML( $msg->parseAsBlock() );
2347 $this->addWikiMsgArray( $msg, $params );
2350 $this->returnToMain();
2354 * Output a standard permission error page
2356 * @param array $errors Error message keys
2357 * @param string $action Action that was denied or null if unknown
2359 public function showPermissionsErrorPage( array $errors, $action = null ) {
2360 // For some action (read, edit, create and upload), display a "login to do this action"
2361 // error if all of the following conditions are met:
2362 // 1. the user is not logged in
2363 // 2. the only error is insufficient permissions (i.e. no block or something else)
2364 // 3. the error can be avoided simply by logging in
2365 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2366 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2367 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2368 && ( User
::groupHasPermission( 'user', $action )
2369 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2371 $displayReturnto = null;
2373 # Due to bug 32276, if a user does not have read permissions,
2374 # $this->getTitle() will just give Special:Badtitle, which is
2375 # not especially useful as a returnto parameter. Use the title
2376 # from the request instead, if there was one.
2377 $request = $this->getRequest();
2378 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2379 if ( $action == 'edit' ) {
2380 $msg = 'whitelistedittext';
2381 $displayReturnto = $returnto;
2382 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2383 $msg = 'nocreatetext';
2384 } elseif ( $action == 'upload' ) {
2385 $msg = 'uploadnologintext';
2387 $msg = 'loginreqpagetext';
2388 $displayReturnto = Title
::newMainPage();
2394 $query['returnto'] = $returnto->getPrefixedText();
2396 if ( !$request->wasPosted() ) {
2397 $returntoquery = $request->getValues();
2398 unset( $returntoquery['title'] );
2399 unset( $returntoquery['returnto'] );
2400 unset( $returntoquery['returntoquery'] );
2401 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2404 $loginLink = Linker
::linkKnown(
2405 SpecialPage
::getTitleFor( 'Userlogin' ),
2406 $this->msg( 'loginreqlink' )->escaped(),
2411 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2412 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2414 # Don't return to a page the user can't read otherwise
2415 # we'll end up in a pointless loop
2416 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2417 $this->returnToMain( null, $displayReturnto );
2420 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2421 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2426 * Display an error page indicating that a given version of MediaWiki is
2427 * required to use it
2429 * @param mixed $version The version of MediaWiki needed to use the page
2431 public function versionRequired( $version ) {
2432 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2434 $this->addWikiMsg( 'versionrequiredtext', $version );
2435 $this->returnToMain();
2439 * Format a list of error messages
2441 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2442 * @param string $action Action that was denied or null if unknown
2443 * @return string The wikitext error-messages, formatted into a list.
2445 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2446 if ( $action == null ) {
2447 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2449 $action_desc = $this->msg( "action-$action" )->plain();
2451 'permissionserrorstext-withaction',
2454 )->plain() . "\n\n";
2457 if ( count( $errors ) > 1 ) {
2458 $text .= '<ul class="permissions-errors">' . "\n";
2460 foreach ( $errors as $error ) {
2462 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2467 $text .= "<div class=\"permissions-errors\">\n" .
2468 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2476 * Display a page stating that the Wiki is in read-only mode.
2477 * Should only be called after wfReadOnly() has returned true.
2479 * Historically, this function was used to show the source of the page that the user
2480 * was trying to edit and _also_ permissions error messages. The relevant code was
2481 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2483 * @deprecated since 1.25; throw the exception directly
2484 * @throws ReadOnlyError
2486 public function readOnlyPage() {
2487 if ( func_num_args() > 0 ) {
2488 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2491 throw new ReadOnlyError
;
2495 * Turn off regular page output and return an error response
2496 * for when rate limiting has triggered.
2498 * @deprecated since 1.25; throw the exception directly
2500 public function rateLimited() {
2501 wfDeprecated( __METHOD__
, '1.25' );
2502 throw new ThrottledError
;
2506 * Show a warning about slave lag
2508 * If the lag is higher than $wgSlaveLagCritical seconds,
2509 * then the warning is a bit more obvious. If the lag is
2510 * lower than $wgSlaveLagWarning, then no warning is shown.
2512 * @param int $lag Slave lag
2514 public function showLagWarning( $lag ) {
2515 $config = $this->getConfig();
2516 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2517 $message = $lag < $config->get( 'SlaveLagCritical' )
2520 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2521 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2525 public function showFatalError( $message ) {
2526 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2528 $this->addHTML( $message );
2531 public function showUnexpectedValueError( $name, $val ) {
2532 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2535 public function showFileCopyError( $old, $new ) {
2536 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2539 public function showFileRenameError( $old, $new ) {
2540 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2543 public function showFileDeleteError( $name ) {
2544 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2547 public function showFileNotFoundError( $name ) {
2548 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2552 * Add a "return to" link pointing to a specified title
2554 * @param Title $title Title to link
2555 * @param array $query Query string parameters
2556 * @param string $text Text of the link (input is not escaped)
2557 * @param array $options Options array to pass to Linker
2559 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2560 $link = $this->msg( 'returnto' )->rawParams(
2561 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2562 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2566 * Add a "return to" link pointing to a specified title,
2567 * or the title indicated in the request, or else the main page
2569 * @param mixed $unused
2570 * @param Title|string $returnto Title or String to return to
2571 * @param string $returntoquery Query string for the return to link
2573 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2574 if ( $returnto == null ) {
2575 $returnto = $this->getRequest()->getText( 'returnto' );
2578 if ( $returntoquery == null ) {
2579 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2582 if ( $returnto === '' ) {
2583 $returnto = Title
::newMainPage();
2586 if ( is_object( $returnto ) ) {
2587 $titleObj = $returnto;
2589 $titleObj = Title
::newFromText( $returnto );
2591 if ( !is_object( $titleObj ) ) {
2592 $titleObj = Title
::newMainPage();
2595 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2599 * @param Skin $sk The given Skin
2600 * @param bool $includeStyle Unused
2601 * @return string The doctype, opening "<html>", and head element.
2603 public function headElement( Skin
$sk, $includeStyle = true ) {
2606 $userdir = $this->getLanguage()->getDir();
2607 $sitedir = $wgContLang->getDir();
2610 $pieces[] = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2612 if ( $this->getHTMLTitle() == '' ) {
2613 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2616 $openHead = Html
::openElement( 'head' );
2618 $pieces[] = $openHead;
2621 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2622 // Add <meta charset="UTF-8">
2623 // This should be before <title> since it defines the charset used by
2624 // text including the text inside <title>.
2625 // The spec recommends defining XHTML5's charset using the XML declaration
2627 // Our XML declaration is output by Html::htmlHeader.
2628 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2629 // http://www.whatwg.org/html/semantics.html#charset
2630 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2633 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2634 $pieces[] = $this->getInlineHeadScripts();
2635 $pieces[] = $this->buildCssLinks();
2636 $pieces[] = $this->getExternalHeadScripts();
2638 foreach ( $this->getHeadLinksArray() as $item ) {
2642 foreach ( $this->mHeadItems
as $item ) {
2646 $closeHead = Html
::closeElement( 'head' );
2648 $pieces[] = $closeHead;
2652 $bodyClasses[] = 'mediawiki';
2654 # Classes for LTR/RTL directionality support
2655 $bodyClasses[] = $userdir;
2656 $bodyClasses[] = "sitedir-$sitedir";
2658 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2659 # A <body> class is probably not the best way to do this . . .
2660 $bodyClasses[] = 'capitalize-all-nouns';
2663 // Parser feature migration class
2664 // The idea is that this will eventually be removed, after the wikitext
2665 // which requires it is cleaned up.
2666 $bodyClasses[] = 'mw-hide-empty-elt';
2668 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2669 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2671 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2674 // While the implode() is not strictly needed, it's used for backwards compatibility
2675 // (this used to be built as a string and hooks likely still expect that).
2676 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2678 // Allow skins and extensions to add body attributes they need
2679 $sk->addToBodyAttributes( $this, $bodyAttrs );
2680 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2682 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2684 return WrappedStringList
::join( "\n", $pieces );
2688 * Get a ResourceLoader object associated with this OutputPage
2690 * @return ResourceLoader
2692 public function getResourceLoader() {
2693 if ( is_null( $this->mResourceLoader
) ) {
2694 $this->mResourceLoader
= new ResourceLoader(
2696 LoggerFactory
::getInstance( 'resourceloader' )
2699 return $this->mResourceLoader
;
2703 * Construct neccecary html and loader preset states to load modules on a page.
2705 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2707 * @param array|string $modules One or more module names
2708 * @param string $only ResourceLoaderModule TYPE_ class constant
2709 * @param array $extraQuery [optional] Array with extra query parameters for the request
2710 * @return array A list of HTML strings and array of client loader preset states
2712 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2713 $modules = (array)$modules;
2716 // List of html strings
2718 // Associative array of module names and their states
2722 if ( !count( $modules ) ) {
2726 if ( count( $modules ) > 1 ) {
2727 // Remove duplicate module requests
2728 $modules = array_unique( $modules );
2729 // Sort module names so requests are more uniform
2732 if ( ResourceLoader
::inDebugMode() ) {
2733 // Recursively call us for every item
2734 foreach ( $modules as $name ) {
2735 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2736 $links['html'] = array_merge( $links['html'], $link['html'] );
2737 $links['states'] +
= $link['states'];
2743 if ( !is_null( $this->mTarget
) ) {
2744 $extraQuery['target'] = $this->mTarget
;
2747 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2748 $sortedModules = [];
2749 $resourceLoader = $this->getResourceLoader();
2750 foreach ( $modules as $name ) {
2751 $module = $resourceLoader->getModule( $name );
2752 # Check that we're allowed to include this module on this page
2754 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2755 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2756 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2757 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2758 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2759 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2760 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2765 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2766 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
2767 $logger = $resourceLoader->getLogger();
2768 $logger->debug( 'Unexpected general module "{module}" in styles queue.', [
2772 $links['states'][$name] = 'ready';
2776 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2779 foreach ( $sortedModules as $source => $groups ) {
2780 foreach ( $groups as $group => $grpModules ) {
2781 // Special handling for user-specific groups
2783 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2784 $user = $this->getUser()->getName();
2787 // Create a fake request based on the one we are about to make so modules return
2788 // correct timestamp and emptiness data
2789 $query = ResourceLoader
::makeLoaderQuery(
2790 [], // modules; not determined yet
2791 $this->getLanguage()->getCode(),
2792 $this->getSkin()->getSkinName(),
2794 null, // version; not determined yet
2795 ResourceLoader
::inDebugMode(),
2796 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2797 $this->isPrintable(),
2798 $this->getRequest()->getBool( 'handheld' ),
2801 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2803 // Extract modules that know they're empty and see if we have one or more
2806 foreach ( $grpModules as $key => $module ) {
2807 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2808 // If we're only getting the styles, we don't need to do anything for empty modules.
2809 if ( $module->isKnownEmpty( $context ) ) {
2810 unset( $grpModules[$key] );
2811 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2812 $links['states'][$key] = 'ready';
2816 $isRaw |
= $module->isRaw();
2819 // If there are no non-empty modules, skip this group
2820 if ( count( $grpModules ) === 0 ) {
2824 // Inline private modules. These can't be loaded through load.php for security
2825 // reasons, see bug 34907. Note that these modules should be loaded from
2826 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2827 // properly use them as dependencies (bug 30914)
2828 if ( $group === 'private' ) {
2829 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2830 $links['html'][] = Html
::inlineStyle(
2831 $resourceLoader->makeModuleResponse( $context, $grpModules )
2834 $links['html'][] = ResourceLoader
::makeInlineScript(
2835 $resourceLoader->makeModuleResponse( $context, $grpModules )
2841 // Special handling for the user group; because users might change their stuff
2842 // on-wiki like user pages, or user preferences; we need to find the highest
2843 // timestamp of these user-changeable modules so we can ensure cache misses on change
2844 // This should NOT be done for the site group (bug 27564) because anons get that too
2845 // and we shouldn't be putting timestamps in CDN-cached HTML
2847 if ( $group === 'user' ) {
2848 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2851 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2852 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2853 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2855 // Automatically select style/script elements
2856 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2857 $link = Html
::linkedStyle( $url );
2859 if ( $context->getRaw() ||
$isRaw ) {
2860 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2861 $link = Html
::element( 'script', [
2862 // In SpecialJavaScriptTest, QUnit must load synchronous
2863 'async' => !isset( $extraQuery['sync'] ),
2867 $link = ResourceLoader
::makeInlineScript(
2868 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
2872 // For modules requested directly in the html via <script> or mw.loader.load
2873 // tell mw.loader they are being loading to prevent duplicate requests.
2874 foreach ( $grpModules as $key => $module ) {
2875 // Don't output state=loading for the startup module.
2876 if ( $key !== 'startup' ) {
2877 $links['states'][$key] = 'loading';
2882 if ( $group == 'noscript' ) {
2883 $links['html'][] = Html
::rawElement( 'noscript', [], $link );
2885 $links['html'][] = $link;
2894 * Build html output from an array of links from makeResourceLoaderLink.
2895 * @param array $links
2896 * @return string|WrappedStringList HTML
2898 protected static function getHtmlFromLoaderLinks( array $links ) {
2901 foreach ( $links as $link ) {
2902 if ( !is_array( $link ) ) {
2905 $html = array_merge( $html, $link['html'] );
2906 $states +
= $link['states'];
2909 // Filter out empty values
2910 $html = array_filter( $html, 'strlen' );
2913 array_unshift( $html, ResourceLoader
::makeInlineScript(
2914 ResourceLoader
::makeLoaderStateScript( $states )
2918 return WrappedString
::join( "\n", $html );
2922 * JS stuff to put in the "<head>". This is the startup module, config
2923 * vars and modules marked with position 'top'
2925 * @return string HTML fragment
2927 function getHeadScripts() {
2928 return $this->getInlineHeadScripts() . $this->getExternalHeadScripts();
2932 * <script src="..."> tags for "<head>".This is the startup module
2933 * and other modules marked with position 'top'.
2935 * @return string|WrappedStringList HTML
2937 function getExternalHeadScripts() {
2938 // Startup - this provides the client with the module
2939 // manifest and loads jquery and mediawiki base modules
2941 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
2942 return self
::getHtmlFromLoaderLinks( $links );
2946 * Inline "<script>" tags to put in "<head>".
2948 * @return string|WrappedStringList HTML
2950 function getInlineHeadScripts() {
2953 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
2954 // Must be done synchronously on every page to avoid flashes of wrong content.
2955 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
2956 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
2957 // For the performance benefit of the majority, this is added unconditionally here and is
2958 // then fixed up by the startup module for unsupported browsers.
2959 $links[] = Html
::inlineScript(
2960 'document.documentElement.className = document.documentElement.className'
2961 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
2964 // Load config before anything else
2965 $links[] = ResourceLoader
::makeInlineScript(
2966 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2969 // Load embeddable private modules before any loader links
2970 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2971 // in mw.loader.implement() calls and deferred until mw.user is available
2972 $embedScripts = [ 'user.options' ];
2973 $links[] = $this->makeResourceLoaderLink(
2975 ResourceLoaderModule
::TYPE_COMBINED
2977 // Separate user.tokens as otherwise caching will be allowed (T84960)
2978 $links[] = $this->makeResourceLoaderLink(
2980 ResourceLoaderModule
::TYPE_COMBINED
2983 // Modules requests - let the client calculate dependencies and batch requests as it likes
2984 // Only load modules that have marked themselves for loading at the top
2985 $modules = $this->getModules( true, 'top' );
2987 $links[] = ResourceLoader
::makeInlineScript(
2988 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
2992 // "Scripts only" modules marked for top inclusion
2993 $links[] = $this->makeResourceLoaderLink(
2994 $this->getModuleScripts( true, 'top' ),
2995 ResourceLoaderModule
::TYPE_SCRIPTS
2998 return self
::getHtmlFromLoaderLinks( $links );
3002 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3003 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3004 * site JS, and user JS.
3006 * @param bool $unused Previously used to let this method change its output based
3007 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3008 * @return string|WrappedStringList HTML
3010 function getScriptsForBottomQueue( $unused = null ) {
3011 // Scripts "only" requests marked for bottom inclusion
3012 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3015 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3016 ResourceLoaderModule
::TYPE_SCRIPTS
3019 // Modules requests - let the client calculate dependencies and batch requests as it likes
3020 // Only load modules that have marked themselves for loading at the bottom
3021 $modules = $this->getModules( true, 'bottom' );
3023 $links[] = ResourceLoader
::makeInlineScript(
3024 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
3029 $links[] = $this->mScripts
;
3031 // Add user JS if enabled
3032 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3033 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3034 if ( $this->getConfig()->get( 'AllowUserJs' )
3035 && $this->getUser()->isLoggedIn()
3036 && $this->getTitle()
3037 && $this->getTitle()->isJsSubpage()
3038 && $this->userCanPreview()
3040 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3041 // and include the draft contents as a raw script instead.
3042 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3043 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3045 // Load the previewed JS
3046 $links[] = ResourceLoader
::makeInlineScript(
3047 Xml
::encodeJsCall( 'mw.loader.using', [
3051 . Xml
::encodeJsCall( '$.globalEval', [
3052 $this->getRequest()->getText( 'wpTextbox1' )
3059 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3060 // asynchronously and may arrive *after* the inline script here. So the previewed code
3061 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3062 // Similarly, when previewing ./common.js and the user module does arrive first,
3063 // it will arrive without common.js and the inline script runs after.
3064 // Thus running common after the excluded subpage.
3066 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3067 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3070 return self
::getHtmlFromLoaderLinks( $links );
3074 * JS stuff to put at the bottom of the "<body>"
3077 function getBottomScripts() {
3078 return $this->getScriptsForBottomQueue();
3082 * Get the javascript config vars to include on this page
3084 * @return array Array of javascript config vars
3087 public function getJsConfigVars() {
3088 return $this->mJsConfigVars
;
3092 * Add one or more variables to be set in mw.config in JavaScript
3094 * @param string|array $keys Key or array of key/value pairs
3095 * @param mixed $value [optional] Value of the configuration variable
3097 public function addJsConfigVars( $keys, $value = null ) {
3098 if ( is_array( $keys ) ) {
3099 foreach ( $keys as $key => $value ) {
3100 $this->mJsConfigVars
[$key] = $value;
3105 $this->mJsConfigVars
[$keys] = $value;
3109 * Get an array containing the variables to be set in mw.config in JavaScript.
3111 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3112 * - in other words, page-independent/site-wide variables (without state).
3113 * You will only be adding bloat to the html page and causing page caches to
3114 * have to be purged on configuration changes.
3117 public function getJSVars() {
3122 $canonicalSpecialPageName = false; # bug 21115
3124 $title = $this->getTitle();
3125 $ns = $title->getNamespace();
3126 $canonicalNamespace = MWNamespace
::exists( $ns )
3127 ? MWNamespace
::getCanonicalName( $ns )
3128 : $title->getNsText();
3130 $sk = $this->getSkin();
3131 // Get the relevant title so that AJAX features can use the correct page name
3132 // when making API requests from certain special pages (bug 34972).
3133 $relevantTitle = $sk->getRelevantTitle();
3134 $relevantUser = $sk->getRelevantUser();
3136 if ( $ns == NS_SPECIAL
) {
3137 list( $canonicalSpecialPageName, /*...*/ ) =
3138 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3139 } elseif ( $this->canUseWikiPage() ) {
3140 $wikiPage = $this->getWikiPage();
3141 $curRevisionId = $wikiPage->getLatest();
3142 $articleId = $wikiPage->getId();
3145 $lang = $title->getPageViewLanguage();
3147 // Pre-process information
3148 $separatorTransTable = $lang->separatorTransformTable();
3149 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3150 $compactSeparatorTransTable = [
3151 implode( "\t", array_keys( $separatorTransTable ) ),
3152 implode( "\t", $separatorTransTable ),
3154 $digitTransTable = $lang->digitTransformTable();
3155 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3156 $compactDigitTransTable = [
3157 implode( "\t", array_keys( $digitTransTable ) ),
3158 implode( "\t", $digitTransTable ),
3161 $user = $this->getUser();
3164 'wgCanonicalNamespace' => $canonicalNamespace,
3165 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3166 'wgNamespaceNumber' => $title->getNamespace(),
3167 'wgPageName' => $title->getPrefixedDBkey(),
3168 'wgTitle' => $title->getText(),
3169 'wgCurRevisionId' => $curRevisionId,
3170 'wgRevisionId' => (int)$this->getRevisionId(),
3171 'wgArticleId' => $articleId,
3172 'wgIsArticle' => $this->isArticle(),
3173 'wgIsRedirect' => $title->isRedirect(),
3174 'wgAction' => Action
::getActionName( $this->getContext() ),
3175 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3176 'wgUserGroups' => $user->getEffectiveGroups(),
3177 'wgCategories' => $this->getCategories(),
3178 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3179 'wgPageContentLanguage' => $lang->getCode(),
3180 'wgPageContentModel' => $title->getContentModel(),
3181 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3182 'wgDigitTransformTable' => $compactDigitTransTable,
3183 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3184 'wgMonthNames' => $lang->getMonthNamesArray(),
3185 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3186 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3187 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3188 'wgRequestId' => WebRequest
::getRequestId(),
3191 if ( $user->isLoggedIn() ) {
3192 $vars['wgUserId'] = $user->getId();
3193 $vars['wgUserEditCount'] = $user->getEditCount();
3194 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3195 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3196 // Get the revision ID of the oldest new message on the user's talk
3197 // page. This can be used for constructing new message alerts on
3199 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3202 if ( $wgContLang->hasVariants() ) {
3203 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3205 // Same test as SkinTemplate
3206 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3207 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3209 foreach ( $title->getRestrictionTypes() as $type ) {
3210 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3213 if ( $title->isMainPage() ) {
3214 $vars['wgIsMainPage'] = true;
3217 if ( $this->mRedirectedFrom
) {
3218 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3221 if ( $relevantUser ) {
3222 $vars['wgRelevantUserName'] = $relevantUser->getName();
3225 // Allow extensions to add their custom variables to the mw.config map.
3226 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3227 // page-dependant but site-wide (without state).
3228 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3229 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3231 // Merge in variables from addJsConfigVars last
3232 return array_merge( $vars, $this->getJsConfigVars() );
3236 * To make it harder for someone to slip a user a fake
3237 * user-JavaScript or user-CSS preview, a random token
3238 * is associated with the login session. If it's not
3239 * passed back with the preview request, we won't render
3244 public function userCanPreview() {
3245 $request = $this->getRequest();
3247 $request->getVal( 'action' ) !== 'submit' ||
3248 !$request->getCheck( 'wpPreview' ) ||
3249 !$request->wasPosted()
3254 $user = $this->getUser();
3255 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3259 $title = $this->getTitle();
3260 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3263 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3264 // Don't execute another user's CSS or JS on preview (T85855)
3268 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3269 if ( count( $errors ) !== 0 ) {
3277 * @return array Array in format "link name or number => 'link html'".
3279 public function getHeadLinksArray() {
3283 $config = $this->getConfig();
3285 $canonicalUrl = $this->mCanonicalUrl
;
3287 $tags['meta-generator'] = Html
::element( 'meta', [
3288 'name' => 'generator',
3289 'content' => "MediaWiki $wgVersion",
3292 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3293 $tags['meta-referrer'] = Html
::element( 'meta', [
3294 'name' => 'referrer',
3295 'content' => $config->get( 'ReferrerPolicy' )
3299 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3300 if ( $p !== 'index,follow' ) {
3301 // http://www.robotstxt.org/wc/meta-user.html
3302 // Only show if it's different from the default robots policy
3303 $tags['meta-robots'] = Html
::element( 'meta', [
3309 foreach ( $this->mMetatags
as $tag ) {
3310 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3312 $tag[0] = substr( $tag[0], 5 );
3316 $tagName = "meta-{$tag[0]}";
3317 if ( isset( $tags[$tagName] ) ) {
3318 $tagName .= $tag[1];
3320 $tags[$tagName] = Html
::element( 'meta',
3323 'content' => $tag[1]
3328 foreach ( $this->mLinktags
as $tag ) {
3329 $tags[] = Html
::element( 'link', $tag );
3332 # Universal edit button
3333 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3334 $user = $this->getUser();
3335 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3336 && ( $this->getTitle()->exists() ||
3337 $this->getTitle()->quickUserCan( 'create', $user ) )
3339 // Original UniversalEditButton
3340 $msg = $this->msg( 'edit' )->text();
3341 $tags['universal-edit-button'] = Html
::element( 'link', [
3342 'rel' => 'alternate',
3343 'type' => 'application/x-wiki',
3345 'href' => $this->getTitle()->getEditURL(),
3347 // Alternate edit link
3348 $tags['alternative-edit'] = Html
::element( 'link', [
3351 'href' => $this->getTitle()->getEditURL(),
3356 # Generally the order of the favicon and apple-touch-icon links
3357 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3358 # uses whichever one appears later in the HTML source. Make sure
3359 # apple-touch-icon is specified first to avoid this.
3360 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3361 $tags['apple-touch-icon'] = Html
::element( 'link', [
3362 'rel' => 'apple-touch-icon',
3363 'href' => $config->get( 'AppleTouchIcon' )
3367 if ( $config->get( 'Favicon' ) !== false ) {
3368 $tags['favicon'] = Html
::element( 'link', [
3369 'rel' => 'shortcut icon',
3370 'href' => $config->get( 'Favicon' )
3374 # OpenSearch description link
3375 $tags['opensearch'] = Html
::element( 'link', [
3377 'type' => 'application/opensearchdescription+xml',
3378 'href' => wfScript( 'opensearch_desc' ),
3379 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3382 if ( $config->get( 'EnableAPI' ) ) {
3383 # Real Simple Discovery link, provides auto-discovery information
3384 # for the MediaWiki API (and potentially additional custom API
3385 # support such as WordPress or Twitter-compatible APIs for a
3386 # blogging extension, etc)
3387 $tags['rsd'] = Html
::element( 'link', [
3389 'type' => 'application/rsd+xml',
3390 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3391 // Whether RSD accepts relative or protocol-relative URLs is completely
3392 // undocumented, though.
3393 'href' => wfExpandUrl( wfAppendQuery(
3395 [ 'action' => 'rsd' ] ),
3402 if ( !$config->get( 'DisableLangConversion' ) ) {
3403 $lang = $this->getTitle()->getPageLanguage();
3404 if ( $lang->hasVariants() ) {
3405 $variants = $lang->getVariants();
3406 foreach ( $variants as $variant ) {
3407 $tags["variant-$variant"] = Html
::element( 'link', [
3408 'rel' => 'alternate',
3409 'hreflang' => wfBCP47( $variant ),
3410 'href' => $this->getTitle()->getLocalURL(
3411 [ 'variant' => $variant ] )
3415 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3416 $tags["variant-x-default"] = Html
::element( 'link', [
3417 'rel' => 'alternate',
3418 'hreflang' => 'x-default',
3419 'href' => $this->getTitle()->getLocalURL() ] );
3424 if ( $this->copyrightUrl
!== null ) {
3425 $copyright = $this->copyrightUrl
;
3428 if ( $config->get( 'RightsPage' ) ) {
3429 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3432 $copyright = $copy->getLocalURL();
3436 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3437 $copyright = $config->get( 'RightsUrl' );
3442 $tags['copyright'] = Html
::element( 'link', [
3443 'rel' => 'copyright',
3444 'href' => $copyright ]
3449 if ( $config->get( 'Feed' ) ) {
3452 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3453 # Use the page name for the title. In principle, this could
3454 # lead to issues with having the same name for different feeds
3455 # corresponding to the same page, but we can't avoid that at
3458 $feedLinks[] = $this->feedLink(
3461 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3463 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3468 # Recent changes feed should appear on every page (except recentchanges,
3469 # that would be redundant). Put it after the per-page feed to avoid
3470 # changing existing behavior. It's still available, probably via a
3471 # menu in your browser. Some sites might have a different feed they'd
3472 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3473 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3474 # If so, use it instead.
3475 $sitename = $config->get( 'Sitename' );
3476 if ( $config->get( 'OverrideSiteFeed' ) ) {
3477 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3478 // Note, this->feedLink escapes the url.
3479 $feedLinks[] = $this->feedLink(
3482 $this->msg( "site-{$type}-feed", $sitename )->text()
3485 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3486 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3487 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3488 $feedLinks[] = $this->feedLink(
3490 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3491 # For grep: 'site-rss-feed', 'site-atom-feed'
3492 $this->msg( "site-{$format}-feed", $sitename )->text()
3497 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3498 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3499 # use OutputPage::addFeedLink() instead.
3500 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3502 $tags +
= $feedLinks;
3506 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3507 if ( $canonicalUrl !== false ) {
3508 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3510 if ( $this->isArticleRelated() ) {
3511 // This affects all requests where "setArticleRelated" is true. This is
3512 // typically all requests that show content (query title, curid, oldid, diff),
3513 // and all wikipage actions (edit, delete, purge, info, history etc.).
3514 // It does not apply to File pages and Special pages.
3515 // 'history' and 'info' actions address page metadata rather than the page
3516 // content itself, so they may not be canonicalized to the view page url.
3517 // TODO: this ought to be better encapsulated in the Action class.
3518 $action = Action
::getActionName( $this->getContext() );
3519 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3520 $query = "action={$action}";
3524 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3526 $reqUrl = $this->getRequest()->getRequestURL();
3527 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3531 if ( $canonicalUrl !== false ) {
3532 $tags[] = Html
::element( 'link', [
3533 'rel' => 'canonical',
3534 'href' => $canonicalUrl
3542 * @return string HTML tag links to be put in the header.
3543 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3544 * OutputPage::getHeadLinksArray directly.
3546 public function getHeadLinks() {
3547 wfDeprecated( __METHOD__
, '1.24' );
3548 return implode( "\n", $this->getHeadLinksArray() );
3552 * Generate a "<link rel/>" for a feed.
3554 * @param string $type Feed type
3555 * @param string $url URL to the feed
3556 * @param string $text Value of the "title" attribute
3557 * @return string HTML fragment
3559 private function feedLink( $type, $url, $text ) {
3560 return Html
::element( 'link', [
3561 'rel' => 'alternate',
3562 'type' => "application/$type+xml",
3569 * Add a local or specified stylesheet, with the given media options.
3570 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3572 * @param string $style URL to the file
3573 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3574 * @param string $condition For IE conditional comments, specifying an IE version
3575 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3577 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3580 $options['media'] = $media;
3583 $options['condition'] = $condition;
3586 $options['dir'] = $dir;
3588 $this->styles
[$style] = $options;
3592 * Adds inline CSS styles
3593 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3595 * @param mixed $style_css Inline CSS
3596 * @param string $flip Set to 'flip' to flip the CSS if needed
3598 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3599 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3600 # If wanted, and the interface is right-to-left, flip the CSS
3601 $style_css = CSSJanus
::transform( $style_css, true, false );
3603 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3607 * Build a set of "<link>" elements for stylesheets specified in the $this->styles array.
3609 * @return string|WrappedStringList HTML
3611 public function buildCssLinks() {
3614 $this->getSkin()->setupSkinUserCss( $this );
3616 // Add ResourceLoader styles
3617 // Split the styles into these groups
3626 $otherTags = []; // Tags to append after the normal <link> tags
3627 $resourceLoader = $this->getResourceLoader();
3629 $moduleStyles = $this->getModuleStyles();
3631 // Per-site custom styles
3632 $moduleStyles[] = 'site.styles';
3633 $moduleStyles[] = 'noscript';
3635 // Per-user custom styles
3636 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3637 && $this->userCanPreview()
3639 // We're on a preview of a CSS subpage
3640 // Exclude this page from the user module in case it's in there (bug 26283)
3641 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
,
3642 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3644 $otherTags = array_merge( $otherTags, $link['html'] );
3646 // Load the previewed CSS
3647 // If needed, Janus it first. This is user-supplied CSS, so it's
3648 // assumed to be right for the content language directionality.
3649 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3650 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3651 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3653 $otherTags[] = Html
::inlineStyle( $previewedCSS );
3655 // Load the user styles normally
3656 $moduleStyles[] = 'user';
3659 // Per-user preference styles
3660 $moduleStyles[] = 'user.cssprefs';
3662 foreach ( $moduleStyles as $name ) {
3663 $module = $resourceLoader->getModule( $name );
3667 if ( $name === 'site.styles' ) {
3668 // HACK: The site module shouldn't be fragmented with a cache group and
3669 // http request. But in order to ensure its styles are separated and after the
3670 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3671 // The scripts remain ungrouped and rides the bottom queue.
3672 $styles['site'][] = $name;
3675 $group = $module->getGroup();
3676 // Modules in groups other than the ones needing special treatment
3677 // (see $styles assignment)
3678 // will be placed in the "other" style category.
3679 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3682 // We want site, private and user styles to override dynamically added
3683 // styles from modules, but we want dynamically added styles to override
3684 // statically added styles from other modules. So the order has to be
3685 // other, dynamic, site, private, user. Add statically added styles for
3687 $links[] = $this->makeResourceLoaderLink(
3689 ResourceLoaderModule
::TYPE_STYLES
3691 // Add normal styles added through addStyle()/addInlineStyle() here
3692 $links[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3693 // Add marker tag to mark the place where the client-side
3694 // loader should inject dynamic styles
3695 // We use a <meta> tag with a made-up name for this because that's valid HTML
3696 $links[] = Html
::element(
3698 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3701 // Add site-specific and user-specific styles
3702 // 'private' at present only contains user.options, so put that before 'user'
3703 // Any future private modules will likely have a similar user-specific character
3704 foreach ( [ 'site', 'noscript', 'private', 'user' ] as $group ) {
3705 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3706 ResourceLoaderModule
::TYPE_STYLES
3710 // Add stuff in $otherTags (previewed user CSS if applicable)
3711 $links[] = implode( '', $otherTags );
3713 return self
::getHtmlFromLoaderLinks( $links );
3719 public function buildCssLinksArray() {
3722 // Add any extension CSS
3723 foreach ( $this->mExtStyles
as $url ) {
3724 $this->addStyle( $url );
3726 $this->mExtStyles
= [];
3728 foreach ( $this->styles
as $file => $options ) {
3729 $link = $this->styleLink( $file, $options );
3731 $links[$file] = $link;
3738 * Generate \<link\> tags for stylesheets
3740 * @param string $style URL to the file
3741 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3742 * @return string HTML fragment
3744 protected function styleLink( $style, array $options ) {
3745 if ( isset( $options['dir'] ) ) {
3746 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3751 if ( isset( $options['media'] ) ) {
3752 $media = self
::transformCssMedia( $options['media'] );
3753 if ( is_null( $media ) ) {
3760 if ( substr( $style, 0, 1 ) == '/' ||
3761 substr( $style, 0, 5 ) == 'http:' ||
3762 substr( $style, 0, 6 ) == 'https:' ) {
3765 $config = $this->getConfig();
3766 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3767 $config->get( 'StyleVersion' );
3770 $link = Html
::linkedStyle( $url, $media );
3772 if ( isset( $options['condition'] ) ) {
3773 $condition = htmlspecialchars( $options['condition'] );
3774 $link = "<!--[if $condition]>$link<![endif]-->";
3780 * Transform path to web-accessible static resource.
3782 * This is used to add a validation hash as query string.
3783 * This aids various behaviors:
3785 * - Put long Cache-Control max-age headers on responses for improved
3786 * cache performance.
3787 * - Get the correct version of a file as expected by the current page.
3788 * - Instantly get the updated version of a file after deployment.
3790 * Avoid using this for urls included in HTML as otherwise clients may get different
3791 * versions of a resource when navigating the site depending on when the page was cached.
3792 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3793 * an external stylesheet).
3796 * @param Config $config
3797 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3798 * @return string URL
3800 public static function transformResourcePath( Config
$config, $path ) {
3802 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3803 if ( $remotePathPrefix === '' ) {
3804 // The configured base path is required to be empty string for
3805 // wikis in the domain root
3808 $remotePath = $remotePathPrefix;
3810 if ( strpos( $path, $remotePath ) !== 0 ) {
3811 // Path is outside wgResourceBasePath, ignore.
3814 $path = RelPath\
getRelativePath( $path, $remotePath );
3815 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3819 * Utility method for transformResourceFilePath().
3821 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3824 * @param string $remotePath URL path prefix that points to $localPath
3825 * @param string $localPath File directory exposed at $remotePath
3826 * @param string $file Path to target file relative to $localPath
3827 * @return string URL
3829 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3830 $hash = md5_file( "$localPath/$file" );
3831 if ( $hash === false ) {
3832 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3835 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3839 * Transform "media" attribute based on request parameters
3841 * @param string $media Current value of the "media" attribute
3842 * @return string Modified value of the "media" attribute, or null to skip
3845 public static function transformCssMedia( $media ) {
3848 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3849 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3851 // Switch in on-screen display for media testing
3853 'printable' => 'print',
3854 'handheld' => 'handheld',
3856 foreach ( $switches as $switch => $targetMedia ) {
3857 if ( $wgRequest->getBool( $switch ) ) {
3858 if ( $media == $targetMedia ) {
3860 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3861 /* This regex will not attempt to understand a comma-separated media_query_list
3863 * Example supported values for $media:
3864 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3865 * Example NOT supported value for $media:
3866 * '3d-glasses, screen, print and resolution > 90dpi'
3868 * If it's a print request, we never want any kind of screen stylesheets
3869 * If it's a handheld request (currently the only other choice with a switch),
3870 * we don't want simple 'screen' but we might want screen queries that
3871 * have a max-width or something, so we'll pass all others on and let the
3872 * client do the query.
3874 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3885 * Add a wikitext-formatted message to the output.
3886 * This is equivalent to:
3888 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3890 public function addWikiMsg( /*...*/ ) {
3891 $args = func_get_args();
3892 $name = array_shift( $args );
3893 $this->addWikiMsgArray( $name, $args );
3897 * Add a wikitext-formatted message to the output.
3898 * Like addWikiMsg() except the parameters are taken as an array
3899 * instead of a variable argument list.
3901 * @param string $name
3902 * @param array $args
3904 public function addWikiMsgArray( $name, $args ) {
3905 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3909 * This function takes a number of message/argument specifications, wraps them in
3910 * some overall structure, and then parses the result and adds it to the output.
3912 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3913 * and so on. The subsequent arguments may be either
3914 * 1) strings, in which case they are message names, or
3915 * 2) arrays, in which case, within each array, the first element is the message
3916 * name, and subsequent elements are the parameters to that message.
3918 * Don't use this for messages that are not in the user's interface language.
3922 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3926 * $wgOut->addWikiText( "<div class='error'>\n"
3927 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3929 * The newline after the opening div is needed in some wikitext. See bug 19226.
3931 * @param string $wrap
3933 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3934 $msgSpecs = func_get_args();
3935 array_shift( $msgSpecs );
3936 $msgSpecs = array_values( $msgSpecs );
3938 foreach ( $msgSpecs as $n => $spec ) {
3939 if ( is_array( $spec ) ) {
3941 $name = array_shift( $args );
3942 if ( isset( $args['options'] ) ) {
3943 unset( $args['options'] );
3945 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3953 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3955 $this->addWikiText( $s );
3959 * Enables/disables TOC, doesn't override __NOTOC__
3963 public function enableTOC( $flag = true ) {
3964 $this->mEnableTOC
= $flag;
3971 public function isTOCEnabled() {
3972 return $this->mEnableTOC
;
3976 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3980 public function enableSectionEditLinks( $flag = true ) {
3981 $this->mEnableSectionEditLinks
= $flag;
3988 public function sectionEditLinksEnabled() {
3989 return $this->mEnableSectionEditLinks
;
3993 * Helper function to setup the PHP implementation of OOUI to use in this request.
3996 * @param String $skinName The Skin name to determine the correct OOUI theme
3997 * @param String $dir Language direction
3999 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
4000 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
4001 // Make keys (skin names) lowercase for case-insensitive matching.
4002 $themes = array_change_key_case( $themes, CASE_LOWER
);
4003 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
4004 // For example, 'OOUI\MediaWikiTheme'.
4005 $themeClass = "OOUI\\{$theme}Theme";
4006 OOUI\Theme
::setSingleton( new $themeClass() );
4007 OOUI\Element
::setDefaultDir( $dir );
4011 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4012 * MediaWiki and this OutputPage instance.
4016 public function enableOOUI() {
4018 strtolower( $this->getSkin()->getSkinName() ),
4019 $this->getLanguage()->getDir()
4021 $this->addModuleStyles( [
4022 'oojs-ui-core.styles',
4023 'oojs-ui.styles.icons',
4024 'oojs-ui.styles.indicators',
4025 'oojs-ui.styles.textures',
4026 'mediawiki.widgets.styles',
4028 // Used by 'skipFunction' of the four 'oojs-ui.styles.*' modules. Please don't treat this as a
4029 // public API or you'll be severely disappointed when T87871 is fixed and it disappears.
4030 $this->addMeta( 'X-OOUI-PHP', '1' );