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 * Get the list of module messages to include on this page
610 * @deprecated since 1.26 Obsolete
611 * @param bool $filter
612 * @param string|null $position
613 * @return array Array of module names
615 public function getModuleMessages( $filter = false, $position = null ) {
616 wfDeprecated( __METHOD__
, '1.26' );
621 * Load messages of one or more ResourceLoader modules.
623 * @deprecated since 1.26 Use addModules() instead
624 * @param string|array $modules Module name (string) or array of module names
626 public function addModuleMessages( $modules ) {
627 wfDeprecated( __METHOD__
, '1.26' );
631 * @return null|string ResourceLoader target
633 public function getTarget() {
634 return $this->mTarget
;
638 * Sets ResourceLoader target for load.php links. If null, will be omitted
640 * @param string|null $target
642 public function setTarget( $target ) {
643 $this->mTarget
= $target;
647 * Get an array of head items
651 function getHeadItemsArray() {
652 return $this->mHeadItems
;
656 * Add or replace a head item to the output
658 * Whenever possible, use more specific options like ResourceLoader modules,
659 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
660 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
661 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
662 * This would be your very LAST fallback.
664 * @param string $name Item name
665 * @param string $value Raw HTML
667 public function addHeadItem( $name, $value ) {
668 $this->mHeadItems
[$name] = $value;
672 * Add one or more head items to the output
675 * @param string|string[] $value Raw HTML
677 public function addHeadItems( $values ) {
678 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
682 * Check if the header item $name is already set
684 * @param string $name Item name
687 public function hasHeadItem( $name ) {
688 return isset( $this->mHeadItems
[$name] );
692 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
695 public function setETag( $tag ) {
699 * Set whether the output should only contain the body of the article,
700 * without any skin, sidebar, etc.
701 * Used e.g. when calling with "action=render".
703 * @param bool $only Whether to output only the body of the article
705 public function setArticleBodyOnly( $only ) {
706 $this->mArticleBodyOnly
= $only;
710 * Return whether the output will contain only the body of the article
714 public function getArticleBodyOnly() {
715 return $this->mArticleBodyOnly
;
719 * Set an additional output property
722 * @param string $name
723 * @param mixed $value
725 public function setProperty( $name, $value ) {
726 $this->mProperties
[$name] = $value;
730 * Get an additional output property
733 * @param string $name
734 * @return mixed Property value or null if not found
736 public function getProperty( $name ) {
737 if ( isset( $this->mProperties
[$name] ) ) {
738 return $this->mProperties
[$name];
745 * checkLastModified tells the client to use the client-cached page if
746 * possible. If successful, the OutputPage is disabled so that
747 * any future call to OutputPage->output() have no effect.
749 * Side effect: sets mLastModified for Last-Modified header
751 * @param string $timestamp
753 * @return bool True if cache-ok headers was sent.
755 public function checkLastModified( $timestamp ) {
756 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
757 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
760 $config = $this->getConfig();
761 if ( !$config->get( 'CachePages' ) ) {
762 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
766 $timestamp = wfTimestamp( TS_MW
, $timestamp );
768 'page' => $timestamp,
769 'user' => $this->getUser()->getTouched(),
770 'epoch' => $config->get( 'CacheEpoch' )
772 if ( $config->get( 'UseSquid' ) ) {
773 // bug 44570: the core page itself may not change, but resources might
774 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
776 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
778 $maxModified = max( $modifiedTimes );
779 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
781 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
782 if ( $clientHeader === false ) {
783 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
787 # IE sends sizes after the date like this:
788 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
789 # this breaks strtotime().
790 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
792 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
793 $clientHeaderTime = strtotime( $clientHeader );
794 MediaWiki\restoreWarnings
();
795 if ( !$clientHeaderTime ) {
797 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
800 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
804 foreach ( $modifiedTimes as $name => $value ) {
805 if ( $info !== '' ) {
808 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
811 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
812 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
813 wfDebug( __METHOD__
. ": effective Last-Modified: " .
814 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
815 if ( $clientHeaderTime < $maxModified ) {
816 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
821 # Give a 304 Not Modified response code and disable body output
822 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
823 ini_set( 'zlib.output_compression', 0 );
824 $this->getRequest()->response()->statusHeader( 304 );
825 $this->sendCacheControl();
828 // Don't output a compressed blob when using ob_gzhandler;
829 // it's technically against HTTP spec and seems to confuse
830 // Firefox when the response gets split over two packets.
831 wfClearOutputBuffers();
837 * Override the last modified timestamp
839 * @param string $timestamp New timestamp, in a format readable by
842 public function setLastModified( $timestamp ) {
843 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
847 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
849 * @param string $policy The literal string to output as the contents of
850 * the meta tag. Will be parsed according to the spec and output in
854 public function setRobotPolicy( $policy ) {
855 $policy = Article
::formatRobotPolicy( $policy );
857 if ( isset( $policy['index'] ) ) {
858 $this->setIndexPolicy( $policy['index'] );
860 if ( isset( $policy['follow'] ) ) {
861 $this->setFollowPolicy( $policy['follow'] );
866 * Set the index policy for the page, but leave the follow policy un-
869 * @param string $policy Either 'index' or 'noindex'.
872 public function setIndexPolicy( $policy ) {
873 $policy = trim( $policy );
874 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
875 $this->mIndexPolicy
= $policy;
880 * Set the follow policy for the page, but leave the index policy un-
883 * @param string $policy Either 'follow' or 'nofollow'.
886 public function setFollowPolicy( $policy ) {
887 $policy = trim( $policy );
888 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
889 $this->mFollowPolicy
= $policy;
894 * Set the new value of the "action text", this will be added to the
895 * "HTML title", separated from it with " - ".
897 * @param string $text New value of the "action text"
899 public function setPageTitleActionText( $text ) {
900 $this->mPageTitleActionText
= $text;
904 * Get the value of the "action text"
908 public function getPageTitleActionText() {
909 return $this->mPageTitleActionText
;
913 * "HTML title" means the contents of "<title>".
914 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
916 * @param string|Message $name
918 public function setHTMLTitle( $name ) {
919 if ( $name instanceof Message
) {
920 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
922 $this->mHTMLtitle
= $name;
927 * Return the "HTML title", i.e. the content of the "<title>" tag.
931 public function getHTMLTitle() {
932 return $this->mHTMLtitle
;
936 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
940 public function setRedirectedFrom( $t ) {
941 $this->mRedirectedFrom
= $t;
945 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
946 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
947 * but not bad tags like \<script\>. This function automatically sets
948 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
949 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
950 * good tags like \<i\> will be dropped entirely.
952 * @param string|Message $name
954 public function setPageTitle( $name ) {
955 if ( $name instanceof Message
) {
956 $name = $name->setContext( $this->getContext() )->text();
959 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
960 # but leave "<i>foobar</i>" alone
961 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
962 $this->mPagetitle
= $nameWithTags;
964 # change "<i>foo&bar</i>" to "foo&bar"
966 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
967 ->inContentLanguage()
972 * Return the "page title", i.e. the content of the \<h1\> tag.
976 public function getPageTitle() {
977 return $this->mPagetitle
;
981 * Set the Title object to use
985 public function setTitle( Title
$t ) {
986 $this->getContext()->setTitle( $t );
990 * Replace the subtitle with $str
992 * @param string|Message $str New value of the subtitle. String should be safe HTML.
994 public function setSubtitle( $str ) {
995 $this->clearSubtitle();
996 $this->addSubtitle( $str );
1000 * Add $str to the subtitle
1002 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1004 public function addSubtitle( $str ) {
1005 if ( $str instanceof Message
) {
1006 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1008 $this->mSubtitle
[] = $str;
1013 * Build message object for a subtitle containing a backlink to a page
1015 * @param Title $title Title to link to
1016 * @param array $query Array of additional parameters to include in the link
1020 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1021 if ( $title->isRedirect() ) {
1022 $query['redirect'] = 'no';
1024 return wfMessage( 'backlinksubtitle' )
1025 ->rawParams( Linker
::link( $title, null, [], $query ) );
1029 * Add a subtitle containing a backlink to a page
1031 * @param Title $title Title to link to
1032 * @param array $query Array of additional parameters to include in the link
1034 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1035 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1039 * Clear the subtitles
1041 public function clearSubtitle() {
1042 $this->mSubtitle
= [];
1050 public function getSubtitle() {
1051 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1055 * Set the page as printable, i.e. it'll be displayed with all
1056 * print styles included
1058 public function setPrintable() {
1059 $this->mPrintable
= true;
1063 * Return whether the page is "printable"
1067 public function isPrintable() {
1068 return $this->mPrintable
;
1072 * Disable output completely, i.e. calling output() will have no effect
1074 public function disable() {
1075 $this->mDoNothing
= true;
1079 * Return whether the output will be completely disabled
1083 public function isDisabled() {
1084 return $this->mDoNothing
;
1088 * Show an "add new section" link?
1092 public function showNewSectionLink() {
1093 return $this->mNewSectionLink
;
1097 * Forcibly hide the new section link?
1101 public function forceHideNewSectionLink() {
1102 return $this->mHideNewSectionLink
;
1106 * Add or remove feed links in the page header
1107 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1108 * for the new version
1109 * @see addFeedLink()
1111 * @param bool $show True: add default feeds, false: remove all feeds
1113 public function setSyndicated( $show = true ) {
1115 $this->setFeedAppendQuery( false );
1117 $this->mFeedLinks
= [];
1122 * Add default feeds to the page header
1123 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1124 * for the new version
1125 * @see addFeedLink()
1127 * @param string $val Query to append to feed links or false to output
1130 public function setFeedAppendQuery( $val ) {
1131 $this->mFeedLinks
= [];
1133 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1134 $query = "feed=$type";
1135 if ( is_string( $val ) ) {
1136 $query .= '&' . $val;
1138 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1143 * Add a feed link to the page header
1145 * @param string $format Feed type, should be a key of $wgFeedClasses
1146 * @param string $href URL
1148 public function addFeedLink( $format, $href ) {
1149 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1150 $this->mFeedLinks
[$format] = $href;
1155 * Should we output feed links for this page?
1158 public function isSyndicated() {
1159 return count( $this->mFeedLinks
) > 0;
1163 * Return URLs for each supported syndication format for this page.
1164 * @return array Associating format keys with URLs
1166 public function getSyndicationLinks() {
1167 return $this->mFeedLinks
;
1171 * Will currently always return null
1175 public function getFeedAppendQuery() {
1176 return $this->mFeedLinksAppendQuery
;
1180 * Set whether the displayed content is related to the source of the
1181 * corresponding article on the wiki
1182 * Setting true will cause the change "article related" toggle to true
1186 public function setArticleFlag( $v ) {
1187 $this->mIsarticle
= $v;
1189 $this->mIsArticleRelated
= $v;
1194 * Return whether the content displayed page is related to the source of
1195 * the corresponding article on the wiki
1199 public function isArticle() {
1200 return $this->mIsarticle
;
1204 * Set whether this page is related an article on the wiki
1205 * Setting false will cause the change of "article flag" toggle to false
1209 public function setArticleRelated( $v ) {
1210 $this->mIsArticleRelated
= $v;
1212 $this->mIsarticle
= false;
1217 * Return whether this page is related an article on the wiki
1221 public function isArticleRelated() {
1222 return $this->mIsArticleRelated
;
1226 * Add new language links
1228 * @param array $newLinkArray Associative array mapping language code to the page
1231 public function addLanguageLinks( array $newLinkArray ) {
1232 $this->mLanguageLinks +
= $newLinkArray;
1236 * Reset the language links and add new language links
1238 * @param array $newLinkArray Associative array mapping language code to the page
1241 public function setLanguageLinks( array $newLinkArray ) {
1242 $this->mLanguageLinks
= $newLinkArray;
1246 * Get the list of language links
1248 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1250 public function getLanguageLinks() {
1251 return $this->mLanguageLinks
;
1255 * Add an array of categories, with names in the keys
1257 * @param array $categories Mapping category name => sort key
1259 public function addCategoryLinks( array $categories ) {
1262 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1266 # Add the links to a LinkBatch
1267 $arr = [ NS_CATEGORY
=> $categories ];
1268 $lb = new LinkBatch
;
1269 $lb->setArray( $arr );
1271 # Fetch existence plus the hiddencat property
1272 $dbr = wfGetDB( DB_SLAVE
);
1273 $fields = array_merge(
1274 LinkCache
::getSelectFields(),
1275 [ 'page_namespace', 'page_title', 'pp_value' ]
1278 $res = $dbr->select( [ 'page', 'page_props' ],
1280 $lb->constructSet( 'page', $dbr ),
1283 [ 'page_props' => [ 'LEFT JOIN', [
1284 'pp_propname' => 'hiddencat',
1289 # Add the results to the link cache
1290 $lb->addResultToCache( LinkCache
::singleton(), $res );
1292 # Set all the values to 'normal'.
1293 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1295 # Mark hidden categories
1296 foreach ( $res as $row ) {
1297 if ( isset( $row->pp_value
) ) {
1298 $categories[$row->page_title
] = 'hidden';
1302 # Add the remaining categories to the skin
1304 'OutputPageMakeCategoryLinks',
1305 [ &$this, $categories, &$this->mCategoryLinks
] )
1307 foreach ( $categories as $category => $type ) {
1308 // array keys will cast numeric category names to ints, so cast back to string
1309 $category = (string)$category;
1310 $origcategory = $category;
1311 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1315 $wgContLang->findVariantLink( $category, $title, true );
1316 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1319 $text = $wgContLang->convertHtml( $title->getText() );
1320 $this->mCategories
[] = $title->getText();
1321 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1327 * Reset the category links (but not the category list) and add $categories
1329 * @param array $categories Mapping category name => sort key
1331 public function setCategoryLinks( array $categories ) {
1332 $this->mCategoryLinks
= [];
1333 $this->addCategoryLinks( $categories );
1337 * Get the list of category links, in a 2-D array with the following format:
1338 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1339 * hidden categories) and $link a HTML fragment with a link to the category
1344 public function getCategoryLinks() {
1345 return $this->mCategoryLinks
;
1349 * Get the list of category names this page belongs to
1351 * @return array Array of strings
1353 public function getCategories() {
1354 return $this->mCategories
;
1358 * Add an array of indicators, with their identifiers as array
1359 * keys and HTML contents as values.
1361 * In case of duplicate keys, existing values are overwritten.
1363 * @param array $indicators
1366 public function setIndicators( array $indicators ) {
1367 $this->mIndicators
= $indicators +
$this->mIndicators
;
1368 // Keep ordered by key
1369 ksort( $this->mIndicators
);
1373 * Get the indicators associated with this page.
1375 * The array will be internally ordered by item keys.
1377 * @return array Keys: identifiers, values: HTML contents
1380 public function getIndicators() {
1381 return $this->mIndicators
;
1385 * Adds help link with an icon via page indicators.
1386 * Link target can be overridden by a local message containing a wikilink:
1387 * the message key is: lowercase action or special page name + '-helppage'.
1388 * @param string $to Target MediaWiki.org page title or encoded URL.
1389 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1392 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1393 $this->addModuleStyles( 'mediawiki.helplink' );
1394 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1396 if ( $overrideBaseUrl ) {
1399 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1400 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1403 $link = Html
::rawElement(
1407 'target' => '_blank',
1408 'class' => 'mw-helplink',
1413 $this->setIndicators( [ 'mw-helplink' => $link ] );
1417 * Do not allow scripts which can be modified by wiki users to load on this page;
1418 * only allow scripts bundled with, or generated by, the software.
1419 * Site-wide styles are controlled by a config setting, since they can be
1420 * used to create a custom skin/theme, but not user-specific ones.
1422 * @todo this should be given a more accurate name
1424 public function disallowUserJs() {
1425 $this->reduceAllowedModules(
1426 ResourceLoaderModule
::TYPE_SCRIPTS
,
1427 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1430 // Site-wide styles are controlled by a config setting, see bug 71621
1431 // for background on why. User styles are never allowed.
1432 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1433 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1435 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1437 $this->reduceAllowedModules(
1438 ResourceLoaderModule
::TYPE_STYLES
,
1444 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1445 * @see ResourceLoaderModule::$origin
1446 * @param string $type ResourceLoaderModule TYPE_ constant
1447 * @return int ResourceLoaderModule ORIGIN_ class constant
1449 public function getAllowedModules( $type ) {
1450 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1451 return min( array_values( $this->mAllowedModules
) );
1453 return isset( $this->mAllowedModules
[$type] )
1454 ?
$this->mAllowedModules
[$type]
1455 : ResourceLoaderModule
::ORIGIN_ALL
;
1460 * Limit the highest level of CSS/JS untrustworthiness allowed.
1462 * If passed the same or a higher level than the current level of untrustworthiness set, the
1463 * level will remain unchanged.
1465 * @param string $type
1466 * @param int $level ResourceLoaderModule class constant
1468 public function reduceAllowedModules( $type, $level ) {
1469 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1473 * Prepend $text to the body HTML
1475 * @param string $text HTML
1477 public function prependHTML( $text ) {
1478 $this->mBodytext
= $text . $this->mBodytext
;
1482 * Append $text to the body HTML
1484 * @param string $text HTML
1486 public function addHTML( $text ) {
1487 $this->mBodytext
.= $text;
1491 * Shortcut for adding an Html::element via addHTML.
1495 * @param string $element
1496 * @param array $attribs
1497 * @param string $contents
1499 public function addElement( $element, array $attribs = [], $contents = '' ) {
1500 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1504 * Clear the body HTML
1506 public function clearHTML() {
1507 $this->mBodytext
= '';
1513 * @return string HTML
1515 public function getHTML() {
1516 return $this->mBodytext
;
1520 * Get/set the ParserOptions object to use for wikitext parsing
1522 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1523 * current ParserOption object
1524 * @return ParserOptions
1526 public function parserOptions( $options = null ) {
1527 if ( $options !== null && !empty( $options->isBogus
) ) {
1528 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1529 // been changed somehow, and keep it if so.
1530 $anonPO = ParserOptions
::newFromAnon();
1531 $anonPO->setEditSection( false );
1532 if ( !$options->matches( $anonPO ) ) {
1533 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1534 $options->isBogus
= false;
1538 if ( !$this->mParserOptions
) {
1539 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1540 // $wgUser isn't unstubbable yet, so don't try to get a
1541 // ParserOptions for it. And don't cache this ParserOptions
1543 $po = ParserOptions
::newFromAnon();
1544 $po->setEditSection( false );
1545 $po->isBogus
= true;
1546 if ( $options !== null ) {
1547 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1552 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1553 $this->mParserOptions
->setEditSection( false );
1556 if ( $options !== null && !empty( $options->isBogus
) ) {
1557 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1559 return wfSetVar( $this->mParserOptions
, null, true );
1561 return wfSetVar( $this->mParserOptions
, $options );
1566 * Set the revision ID which will be seen by the wiki text parser
1567 * for things such as embedded {{REVISIONID}} variable use.
1569 * @param int|null $revid An positive integer, or null
1570 * @return mixed Previous value
1572 public function setRevisionId( $revid ) {
1573 $val = is_null( $revid ) ?
null : intval( $revid );
1574 return wfSetVar( $this->mRevisionId
, $val );
1578 * Get the displayed revision ID
1582 public function getRevisionId() {
1583 return $this->mRevisionId
;
1587 * Set the timestamp of the revision which will be displayed. This is used
1588 * to avoid a extra DB call in Skin::lastModified().
1590 * @param string|null $timestamp
1591 * @return mixed Previous value
1593 public function setRevisionTimestamp( $timestamp ) {
1594 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1598 * Get the timestamp of displayed revision.
1599 * This will be null if not filled by setRevisionTimestamp().
1601 * @return string|null
1603 public function getRevisionTimestamp() {
1604 return $this->mRevisionTimestamp
;
1608 * Set the displayed file version
1610 * @param File|bool $file
1611 * @return mixed Previous value
1613 public function setFileVersion( $file ) {
1615 if ( $file instanceof File
&& $file->exists() ) {
1616 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1618 return wfSetVar( $this->mFileVersion
, $val, true );
1622 * Get the displayed file version
1624 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1626 public function getFileVersion() {
1627 return $this->mFileVersion
;
1631 * Get the templates used on this page
1633 * @return array (namespace => dbKey => revId)
1636 public function getTemplateIds() {
1637 return $this->mTemplateIds
;
1641 * Get the files used on this page
1643 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1646 public function getFileSearchOptions() {
1647 return $this->mImageTimeKeys
;
1651 * Convert wikitext to HTML and add it to the buffer
1652 * Default assumes that the current page title will be used.
1654 * @param string $text
1655 * @param bool $linestart Is this the start of a line?
1656 * @param bool $interface Is this text in the user interface language?
1657 * @throws MWException
1659 public function addWikiText( $text, $linestart = true, $interface = true ) {
1660 $title = $this->getTitle(); // Work around E_STRICT
1662 throw new MWException( 'Title is null' );
1664 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
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?
1674 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1675 $this->addWikiTextTitle( $text, $title, $linestart );
1679 * Add wikitext with a custom Title object and tidy enabled.
1681 * @param string $text Wikitext
1682 * @param Title $title
1683 * @param bool $linestart Is this the start of a line?
1685 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1686 $this->addWikiTextTitle( $text, $title, $linestart, true );
1690 * Add wikitext with tidy enabled
1692 * @param string $text Wikitext
1693 * @param bool $linestart Is this the start of a line?
1695 public function addWikiTextTidy( $text, $linestart = true ) {
1696 $title = $this->getTitle();
1697 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1701 * Add wikitext with a custom Title object
1703 * @param string $text Wikitext
1704 * @param Title $title
1705 * @param bool $linestart Is this the start of a line?
1706 * @param bool $tidy Whether to use tidy
1707 * @param bool $interface Whether it is an interface message
1708 * (for example disables conversion)
1710 public function addWikiTextTitle( $text, Title
$title, $linestart,
1711 $tidy = false, $interface = false
1715 $popts = $this->parserOptions();
1716 $oldTidy = $popts->setTidy( $tidy );
1717 $popts->setInterfaceMessage( (bool)$interface );
1719 $parserOutput = $wgParser->getFreshParser()->parse(
1720 $text, $title, $popts,
1721 $linestart, true, $this->mRevisionId
1724 $popts->setTidy( $oldTidy );
1726 $this->addParserOutput( $parserOutput );
1731 * Add a ParserOutput object, but without Html.
1733 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1734 * @param ParserOutput $parserOutput
1736 public function addParserOutputNoText( $parserOutput ) {
1737 wfDeprecated( __METHOD__
, '1.24' );
1738 $this->addParserOutputMetadata( $parserOutput );
1742 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1743 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1747 * @param ParserOutput $parserOutput
1749 public function addParserOutputMetadata( $parserOutput ) {
1750 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1751 $this->addCategoryLinks( $parserOutput->getCategories() );
1752 $this->setIndicators( $parserOutput->getIndicators() );
1753 $this->mNewSectionLink
= $parserOutput->getNewSection();
1754 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1756 if ( !$parserOutput->isCacheable() ) {
1757 $this->enableClientCache( false );
1759 $this->mNoGallery
= $parserOutput->getNoGallery();
1760 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1761 $this->addModules( $parserOutput->getModules() );
1762 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1763 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1764 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1765 $this->mPreventClickjacking
= $this->mPreventClickjacking
1766 ||
$parserOutput->preventClickjacking();
1768 // Template versioning...
1769 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1770 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1771 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1773 $this->mTemplateIds
[$ns] = $dbks;
1776 // File versioning...
1777 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1778 $this->mImageTimeKeys
[$dbk] = $data;
1781 // Hooks registered in the object
1782 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1783 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1784 list( $hookName, $data ) = $hookInfo;
1785 if ( isset( $parserOutputHooks[$hookName] ) ) {
1786 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1790 // enable OOUI if requested via ParserOutput
1791 if ( $parserOutput->getEnableOOUI() ) {
1792 $this->enableOOUI();
1795 // Link flags are ignored for now, but may in the future be
1796 // used to mark individual language links.
1798 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1799 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1803 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1804 * ParserOutput object, without any other metadata.
1807 * @param ParserOutput $parserOutput
1809 public function addParserOutputContent( $parserOutput ) {
1810 $this->addParserOutputText( $parserOutput );
1812 $this->addModules( $parserOutput->getModules() );
1813 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1814 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1816 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1820 * Add the HTML associated with a ParserOutput object, without any metadata.
1823 * @param ParserOutput $parserOutput
1825 public function addParserOutputText( $parserOutput ) {
1826 $text = $parserOutput->getText();
1827 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1828 $this->addHTML( $text );
1832 * Add everything from a ParserOutput object.
1834 * @param ParserOutput $parserOutput
1836 function addParserOutput( $parserOutput ) {
1837 $this->addParserOutputMetadata( $parserOutput );
1838 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1840 // Touch section edit links only if not previously disabled
1841 if ( $parserOutput->getEditSectionTokens() ) {
1842 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1845 $this->addParserOutputText( $parserOutput );
1849 * Add the output of a QuickTemplate to the output buffer
1851 * @param QuickTemplate $template
1853 public function addTemplate( &$template ) {
1854 $this->addHTML( $template->getHTML() );
1858 * Parse wikitext and return the HTML.
1860 * @param string $text
1861 * @param bool $linestart Is this the start of a line?
1862 * @param bool $interface Use interface language ($wgLang instead of
1863 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1864 * This also disables LanguageConverter.
1865 * @param Language $language Target language object, will override $interface
1866 * @throws MWException
1867 * @return string HTML
1869 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1872 if ( is_null( $this->getTitle() ) ) {
1873 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1876 $popts = $this->parserOptions();
1878 $popts->setInterfaceMessage( true );
1880 if ( $language !== null ) {
1881 $oldLang = $popts->setTargetLanguage( $language );
1884 $parserOutput = $wgParser->getFreshParser()->parse(
1885 $text, $this->getTitle(), $popts,
1886 $linestart, true, $this->mRevisionId
1890 $popts->setInterfaceMessage( false );
1892 if ( $language !== null ) {
1893 $popts->setTargetLanguage( $oldLang );
1896 return $parserOutput->getText();
1900 * Parse wikitext, strip paragraphs, and return the HTML.
1902 * @param string $text
1903 * @param bool $linestart Is this the start of a line?
1904 * @param bool $interface Use interface language ($wgLang instead of
1905 * $wgContLang) while parsing language sensitive magic
1906 * words like GRAMMAR and PLURAL
1907 * @return string HTML
1909 public function parseInline( $text, $linestart = true, $interface = false ) {
1910 $parsed = $this->parse( $text, $linestart, $interface );
1911 return Parser
::stripOuterParagraph( $parsed );
1916 * @deprecated since 1.27 Use setCdnMaxage() instead
1918 public function setSquidMaxage( $maxage ) {
1919 $this->setCdnMaxage( $maxage );
1923 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1925 * @param int $maxage Maximum cache time on the CDN, in seconds.
1927 public function setCdnMaxage( $maxage ) {
1928 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1932 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1934 * @param int $maxage Maximum cache time on the CDN, in seconds
1937 public function lowerCdnMaxage( $maxage ) {
1938 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1939 $this->setCdnMaxage( $this->mCdnMaxage
);
1943 * Use enableClientCache(false) to force it to send nocache headers
1945 * @param bool $state
1949 public function enableClientCache( $state ) {
1950 return wfSetVar( $this->mEnableClientCache
, $state );
1954 * Get the list of cookies that will influence on the cache
1958 function getCacheVaryCookies() {
1960 if ( $cookies === null ) {
1961 $config = $this->getConfig();
1962 $cookies = array_merge(
1963 SessionManager
::singleton()->getVaryCookies(),
1967 $config->get( 'CacheVaryCookies' )
1969 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
1975 * Check if the request has a cache-varying cookie header
1976 * If it does, it's very important that we don't allow public caching
1980 function haveCacheVaryCookies() {
1981 $request = $this->getRequest();
1982 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
1983 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
1984 wfDebug( __METHOD__
. ": found $cookieName\n" );
1988 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1993 * Add an HTTP header that will influence on the cache
1995 * @param string $header Header name
1996 * @param string[]|null $option Options for the Key header. See
1997 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
1998 * for the list of valid options.
2000 public function addVaryHeader( $header, array $option = null ) {
2001 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2002 $this->mVaryHeader
[$header] = [];
2004 if ( !is_array( $option ) ) {
2007 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2011 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2012 * such as Accept-Encoding or Cookie
2016 public function getVaryHeader() {
2017 // If we vary on cookies, let's make sure it's always included here too.
2018 if ( $this->getCacheVaryCookies() ) {
2019 $this->addVaryHeader( 'Cookie' );
2022 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2023 $this->addVaryHeader( $header, $options );
2025 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2029 * Get a complete Key header
2033 public function getKeyHeader() {
2034 $cvCookies = $this->getCacheVaryCookies();
2036 $cookiesOption = [];
2037 foreach ( $cvCookies as $cookieName ) {
2038 $cookiesOption[] = 'param=' . $cookieName;
2040 $this->addVaryHeader( 'Cookie', $cookiesOption );
2042 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2043 $this->addVaryHeader( $header, $options );
2047 foreach ( $this->mVaryHeader
as $header => $option ) {
2048 $newheader = $header;
2049 if ( is_array( $option ) && count( $option ) > 0 ) {
2050 $newheader .= ';' . implode( ';', $option );
2052 $headers[] = $newheader;
2054 $key = 'Key: ' . implode( ',', $headers );
2060 * T23672: Add Accept-Language to Vary and Key headers
2061 * if there's no 'variant' parameter existed in GET.
2064 * /w/index.php?title=Main_page should always be served; but
2065 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2067 function addAcceptLanguage() {
2068 $title = $this->getTitle();
2069 if ( !$title instanceof Title
) {
2073 $lang = $title->getPageLanguage();
2074 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2075 $variants = $lang->getVariants();
2077 foreach ( $variants as $variant ) {
2078 if ( $variant === $lang->getCode() ) {
2081 $aloption[] = 'substr=' . $variant;
2083 // IE and some other browsers use BCP 47 standards in
2084 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2085 // We should handle these too.
2086 $variantBCP47 = wfBCP47( $variant );
2087 if ( $variantBCP47 !== $variant ) {
2088 $aloption[] = 'substr=' . $variantBCP47;
2092 $this->addVaryHeader( 'Accept-Language', $aloption );
2097 * Set a flag which will cause an X-Frame-Options header appropriate for
2098 * edit pages to be sent. The header value is controlled by
2099 * $wgEditPageFrameOptions.
2101 * This is the default for special pages. If you display a CSRF-protected
2102 * form on an ordinary view page, then you need to call this function.
2104 * @param bool $enable
2106 public function preventClickjacking( $enable = true ) {
2107 $this->mPreventClickjacking
= $enable;
2111 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2112 * This can be called from pages which do not contain any CSRF-protected
2115 public function allowClickjacking() {
2116 $this->mPreventClickjacking
= false;
2120 * Get the prevent-clickjacking flag
2125 public function getPreventClickjacking() {
2126 return $this->mPreventClickjacking
;
2130 * Get the X-Frame-Options header value (without the name part), or false
2131 * if there isn't one. This is used by Skin to determine whether to enable
2132 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2136 public function getFrameOptions() {
2137 $config = $this->getConfig();
2138 if ( $config->get( 'BreakFrames' ) ) {
2140 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2141 return $config->get( 'EditPageFrameOptions' );
2147 * Send cache control HTTP headers
2149 public function sendCacheControl() {
2150 $response = $this->getRequest()->response();
2151 $config = $this->getConfig();
2153 $this->addVaryHeader( 'Cookie' );
2154 $this->addAcceptLanguage();
2156 # don't serve compressed data to clients who can't handle it
2157 # maintain different caches for logged-in users and non-logged in ones
2158 $response->header( $this->getVaryHeader() );
2160 if ( $config->get( 'UseKeyHeader' ) ) {
2161 $response->header( $this->getKeyHeader() );
2164 if ( $this->mEnableClientCache
) {
2166 $config->get( 'UseSquid' ) &&
2167 !$response->hasCookies() &&
2168 !SessionManager
::getGlobalSession()->isPersistent() &&
2169 !$this->isPrintable() &&
2170 $this->mCdnMaxage
!= 0 &&
2171 !$this->haveCacheVaryCookies()
2173 if ( $config->get( 'UseESI' ) ) {
2174 # We'll purge the proxy cache explicitly, but require end user agents
2175 # to revalidate against the proxy on each visit.
2176 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2177 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2178 # start with a shorter timeout for initial testing
2179 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2180 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2181 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2182 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2184 # We'll purge the proxy cache for anons explicitly, but require end user agents
2185 # to revalidate against the proxy on each visit.
2186 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2187 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2188 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2189 # start with a shorter timeout for initial testing
2190 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2191 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2192 . ', must-revalidate, max-age=0' );
2195 # We do want clients to cache if they can, but they *must* check for updates
2196 # on revisiting the page.
2197 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2198 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2199 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2201 if ( $this->mLastModified
) {
2202 $response->header( "Last-Modified: {$this->mLastModified}" );
2205 wfDebug( __METHOD__
. ": no caching **", 'private' );
2207 # In general, the absence of a last modified header should be enough to prevent
2208 # the client from using its cache. We send a few other things just to make sure.
2209 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2210 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2211 $response->header( 'Pragma: no-cache' );
2216 * Finally, all the text has been munged and accumulated into
2217 * the object, let's actually output it:
2219 public function output() {
2220 if ( $this->mDoNothing
) {
2224 $response = $this->getRequest()->response();
2225 $config = $this->getConfig();
2227 if ( $this->mRedirect
!= '' ) {
2228 # Standards require redirect URLs to be absolute
2229 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2231 $redirect = $this->mRedirect
;
2232 $code = $this->mRedirectCode
;
2234 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2235 if ( $code == '301' ||
$code == '303' ) {
2236 if ( !$config->get( 'DebugRedirects' ) ) {
2237 $response->statusHeader( $code );
2239 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2241 if ( $config->get( 'VaryOnXFP' ) ) {
2242 $this->addVaryHeader( 'X-Forwarded-Proto' );
2244 $this->sendCacheControl();
2246 $response->header( "Content-Type: text/html; charset=utf-8" );
2247 if ( $config->get( 'DebugRedirects' ) ) {
2248 $url = htmlspecialchars( $redirect );
2249 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2250 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2251 print "</body>\n</html>\n";
2253 $response->header( 'Location: ' . $redirect );
2258 } elseif ( $this->mStatusCode
) {
2259 $response->statusHeader( $this->mStatusCode
);
2262 # Buffer output; final headers may depend on later processing
2265 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2266 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2268 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2269 // jQuery etc. can work correctly.
2270 $response->header( 'X-UA-Compatible: IE=Edge' );
2272 // Prevent framing, if requested
2273 $frameOptions = $this->getFrameOptions();
2274 if ( $frameOptions ) {
2275 $response->header( "X-Frame-Options: $frameOptions" );
2278 if ( $this->mArticleBodyOnly
) {
2279 echo $this->mBodytext
;
2281 $sk = $this->getSkin();
2282 // add skin specific modules
2283 $modules = $sk->getDefaultModules();
2285 // Enforce various default modules for all skins
2287 // Keep this list as small as possible
2289 'mediawiki.page.startup',
2293 // Support for high-density display images if enabled
2294 if ( $config->get( 'ResponsiveImages' ) ) {
2295 $coreModules[] = 'mediawiki.hidpi';
2298 $this->addModules( $coreModules );
2299 foreach ( $modules as $group ) {
2300 $this->addModules( $group );
2302 MWDebug
::addModules( $this );
2304 // Hook that allows last minute changes to the output page, e.g.
2305 // adding of CSS or Javascript by extensions.
2306 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2310 } catch ( Exception
$e ) {
2311 ob_end_clean(); // bug T129657
2317 // This hook allows last minute changes to final overall output by modifying output buffer
2318 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2319 } catch ( Exception
$e ) {
2320 ob_end_clean(); // bug T129657
2324 $this->sendCacheControl();
2331 * Prepare this object to display an error page; disable caching and
2332 * indexing, clear the current text and redirect, set the page's title
2333 * and optionally an custom HTML title (content of the "<title>" tag).
2335 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2336 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2337 * optional, if not passed the "<title>" attribute will be
2338 * based on $pageTitle
2340 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2341 $this->setPageTitle( $pageTitle );
2342 if ( $htmlTitle !== false ) {
2343 $this->setHTMLTitle( $htmlTitle );
2345 $this->setRobotPolicy( 'noindex,nofollow' );
2346 $this->setArticleRelated( false );
2347 $this->enableClientCache( false );
2348 $this->mRedirect
= '';
2349 $this->clearSubtitle();
2354 * Output a standard error page
2356 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2357 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2358 * showErrorPage( 'titlemsg', $messageObject );
2359 * showErrorPage( $titleMessageObject, $messageObject );
2361 * @param string|Message $title Message key (string) for page title, or a Message object
2362 * @param string|Message $msg Message key (string) for page text, or a Message object
2363 * @param array $params Message parameters; ignored if $msg is a Message object
2365 public function showErrorPage( $title, $msg, $params = [] ) {
2366 if ( !$title instanceof Message
) {
2367 $title = $this->msg( $title );
2370 $this->prepareErrorPage( $title );
2372 if ( $msg instanceof Message
) {
2373 if ( $params !== [] ) {
2374 trigger_error( 'Argument ignored: $params. The message parameters argument '
2375 . 'is discarded when the $msg argument is a Message object instead of '
2376 . 'a string.', E_USER_NOTICE
);
2378 $this->addHTML( $msg->parseAsBlock() );
2380 $this->addWikiMsgArray( $msg, $params );
2383 $this->returnToMain();
2387 * Output a standard permission error page
2389 * @param array $errors Error message keys
2390 * @param string $action Action that was denied or null if unknown
2392 public function showPermissionsErrorPage( array $errors, $action = null ) {
2393 // For some action (read, edit, create and upload), display a "login to do this action"
2394 // error if all of the following conditions are met:
2395 // 1. the user is not logged in
2396 // 2. the only error is insufficient permissions (i.e. no block or something else)
2397 // 3. the error can be avoided simply by logging in
2398 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2399 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2400 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2401 && ( User
::groupHasPermission( 'user', $action )
2402 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2404 $displayReturnto = null;
2406 # Due to bug 32276, if a user does not have read permissions,
2407 # $this->getTitle() will just give Special:Badtitle, which is
2408 # not especially useful as a returnto parameter. Use the title
2409 # from the request instead, if there was one.
2410 $request = $this->getRequest();
2411 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2412 if ( $action == 'edit' ) {
2413 $msg = 'whitelistedittext';
2414 $displayReturnto = $returnto;
2415 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2416 $msg = 'nocreatetext';
2417 } elseif ( $action == 'upload' ) {
2418 $msg = 'uploadnologintext';
2420 $msg = 'loginreqpagetext';
2421 $displayReturnto = Title
::newMainPage();
2427 $query['returnto'] = $returnto->getPrefixedText();
2429 if ( !$request->wasPosted() ) {
2430 $returntoquery = $request->getValues();
2431 unset( $returntoquery['title'] );
2432 unset( $returntoquery['returnto'] );
2433 unset( $returntoquery['returntoquery'] );
2434 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2437 $loginLink = Linker
::linkKnown(
2438 SpecialPage
::getTitleFor( 'Userlogin' ),
2439 $this->msg( 'loginreqlink' )->escaped(),
2444 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2445 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2447 # Don't return to a page the user can't read otherwise
2448 # we'll end up in a pointless loop
2449 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2450 $this->returnToMain( null, $displayReturnto );
2453 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2454 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2459 * Display an error page indicating that a given version of MediaWiki is
2460 * required to use it
2462 * @param mixed $version The version of MediaWiki needed to use the page
2464 public function versionRequired( $version ) {
2465 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2467 $this->addWikiMsg( 'versionrequiredtext', $version );
2468 $this->returnToMain();
2472 * Format a list of error messages
2474 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2475 * @param string $action Action that was denied or null if unknown
2476 * @return string The wikitext error-messages, formatted into a list.
2478 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2479 if ( $action == null ) {
2480 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2482 $action_desc = $this->msg( "action-$action" )->plain();
2484 'permissionserrorstext-withaction',
2487 )->plain() . "\n\n";
2490 if ( count( $errors ) > 1 ) {
2491 $text .= '<ul class="permissions-errors">' . "\n";
2493 foreach ( $errors as $error ) {
2495 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2500 $text .= "<div class=\"permissions-errors\">\n" .
2501 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2509 * Display a page stating that the Wiki is in read-only mode.
2510 * Should only be called after wfReadOnly() has returned true.
2512 * Historically, this function was used to show the source of the page that the user
2513 * was trying to edit and _also_ permissions error messages. The relevant code was
2514 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2516 * @deprecated since 1.25; throw the exception directly
2517 * @throws ReadOnlyError
2519 public function readOnlyPage() {
2520 if ( func_num_args() > 0 ) {
2521 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2524 throw new ReadOnlyError
;
2528 * Turn off regular page output and return an error response
2529 * for when rate limiting has triggered.
2531 * @deprecated since 1.25; throw the exception directly
2533 public function rateLimited() {
2534 wfDeprecated( __METHOD__
, '1.25' );
2535 throw new ThrottledError
;
2539 * Show a warning about slave lag
2541 * If the lag is higher than $wgSlaveLagCritical seconds,
2542 * then the warning is a bit more obvious. If the lag is
2543 * lower than $wgSlaveLagWarning, then no warning is shown.
2545 * @param int $lag Slave lag
2547 public function showLagWarning( $lag ) {
2548 $config = $this->getConfig();
2549 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2550 $message = $lag < $config->get( 'SlaveLagCritical' )
2553 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2554 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2558 public function showFatalError( $message ) {
2559 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2561 $this->addHTML( $message );
2564 public function showUnexpectedValueError( $name, $val ) {
2565 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2568 public function showFileCopyError( $old, $new ) {
2569 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2572 public function showFileRenameError( $old, $new ) {
2573 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2576 public function showFileDeleteError( $name ) {
2577 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2580 public function showFileNotFoundError( $name ) {
2581 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2585 * Add a "return to" link pointing to a specified title
2587 * @param Title $title Title to link
2588 * @param array $query Query string parameters
2589 * @param string $text Text of the link (input is not escaped)
2590 * @param array $options Options array to pass to Linker
2592 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2593 $link = $this->msg( 'returnto' )->rawParams(
2594 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2595 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2599 * Add a "return to" link pointing to a specified title,
2600 * or the title indicated in the request, or else the main page
2602 * @param mixed $unused
2603 * @param Title|string $returnto Title or String to return to
2604 * @param string $returntoquery Query string for the return to link
2606 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2607 if ( $returnto == null ) {
2608 $returnto = $this->getRequest()->getText( 'returnto' );
2611 if ( $returntoquery == null ) {
2612 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2615 if ( $returnto === '' ) {
2616 $returnto = Title
::newMainPage();
2619 if ( is_object( $returnto ) ) {
2620 $titleObj = $returnto;
2622 $titleObj = Title
::newFromText( $returnto );
2624 if ( !is_object( $titleObj ) ) {
2625 $titleObj = Title
::newMainPage();
2628 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2632 * @param Skin $sk The given Skin
2633 * @param bool $includeStyle Unused
2634 * @return string The doctype, opening "<html>", and head element.
2636 public function headElement( Skin
$sk, $includeStyle = true ) {
2639 $userdir = $this->getLanguage()->getDir();
2640 $sitedir = $wgContLang->getDir();
2643 $pieces[] = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2645 if ( $this->getHTMLTitle() == '' ) {
2646 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2649 $openHead = Html
::openElement( 'head' );
2651 $pieces[] = $openHead;
2654 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2655 // Add <meta charset="UTF-8">
2656 // This should be before <title> since it defines the charset used by
2657 // text including the text inside <title>.
2658 // The spec recommends defining XHTML5's charset using the XML declaration
2660 // Our XML declaration is output by Html::htmlHeader.
2661 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2662 // http://www.whatwg.org/html/semantics.html#charset
2663 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2666 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2667 $pieces[] = $this->getInlineHeadScripts();
2668 $pieces[] = $this->buildCssLinks();
2669 $pieces[] = $this->getExternalHeadScripts();
2671 foreach ( $this->getHeadLinksArray() as $item ) {
2675 foreach ( $this->mHeadItems
as $item ) {
2679 $closeHead = Html
::closeElement( 'head' );
2681 $pieces[] = $closeHead;
2685 $bodyClasses[] = 'mediawiki';
2687 # Classes for LTR/RTL directionality support
2688 $bodyClasses[] = $userdir;
2689 $bodyClasses[] = "sitedir-$sitedir";
2691 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2692 # A <body> class is probably not the best way to do this . . .
2693 $bodyClasses[] = 'capitalize-all-nouns';
2696 // Parser feature migration class
2697 // The idea is that this will eventually be removed, after the wikitext
2698 // which requires it is cleaned up.
2699 $bodyClasses[] = 'mw-hide-empty-elt';
2701 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2702 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2704 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2707 // While the implode() is not strictly needed, it's used for backwards compatibility
2708 // (this used to be built as a string and hooks likely still expect that).
2709 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2711 // Allow skins and extensions to add body attributes they need
2712 $sk->addToBodyAttributes( $this, $bodyAttrs );
2713 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2715 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2717 return WrappedStringList
::join( "\n", $pieces );
2721 * Get a ResourceLoader object associated with this OutputPage
2723 * @return ResourceLoader
2725 public function getResourceLoader() {
2726 if ( is_null( $this->mResourceLoader
) ) {
2727 $this->mResourceLoader
= new ResourceLoader(
2729 LoggerFactory
::getInstance( 'resourceloader' )
2732 return $this->mResourceLoader
;
2736 * Construct neccecary html and loader preset states to load modules on a page.
2738 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2740 * @param array|string $modules One or more module names
2741 * @param string $only ResourceLoaderModule TYPE_ class constant
2742 * @param array $extraQuery [optional] Array with extra query parameters for the request
2743 * @return array A list of HTML strings and array of client loader preset states
2745 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2746 $modules = (array)$modules;
2749 // List of html strings
2751 // Associative array of module names and their states
2755 if ( !count( $modules ) ) {
2759 if ( count( $modules ) > 1 ) {
2760 // Remove duplicate module requests
2761 $modules = array_unique( $modules );
2762 // Sort module names so requests are more uniform
2765 if ( ResourceLoader
::inDebugMode() ) {
2766 // Recursively call us for every item
2767 foreach ( $modules as $name ) {
2768 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2769 $links['html'] = array_merge( $links['html'], $link['html'] );
2770 $links['states'] +
= $link['states'];
2776 if ( !is_null( $this->mTarget
) ) {
2777 $extraQuery['target'] = $this->mTarget
;
2780 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2781 $sortedModules = [];
2782 $resourceLoader = $this->getResourceLoader();
2783 foreach ( $modules as $name ) {
2784 $module = $resourceLoader->getModule( $name );
2785 # Check that we're allowed to include this module on this page
2787 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2788 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2789 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2790 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2791 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2792 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2793 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2798 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2799 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
2800 $logger = $resourceLoader->getLogger();
2801 $logger->debug( 'Unexpected general module "{module}" in styles queue.', [
2805 $links['states'][$name] = 'ready';
2809 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2812 foreach ( $sortedModules as $source => $groups ) {
2813 foreach ( $groups as $group => $grpModules ) {
2814 // Special handling for user-specific groups
2816 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2817 $user = $this->getUser()->getName();
2820 // Create a fake request based on the one we are about to make so modules return
2821 // correct timestamp and emptiness data
2822 $query = ResourceLoader
::makeLoaderQuery(
2823 [], // modules; not determined yet
2824 $this->getLanguage()->getCode(),
2825 $this->getSkin()->getSkinName(),
2827 null, // version; not determined yet
2828 ResourceLoader
::inDebugMode(),
2829 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2830 $this->isPrintable(),
2831 $this->getRequest()->getBool( 'handheld' ),
2834 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2836 // Extract modules that know they're empty and see if we have one or more
2839 foreach ( $grpModules as $key => $module ) {
2840 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2841 // If we're only getting the styles, we don't need to do anything for empty modules.
2842 if ( $module->isKnownEmpty( $context ) ) {
2843 unset( $grpModules[$key] );
2844 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2845 $links['states'][$key] = 'ready';
2849 $isRaw |
= $module->isRaw();
2852 // If there are no non-empty modules, skip this group
2853 if ( count( $grpModules ) === 0 ) {
2857 // Inline private modules. These can't be loaded through load.php for security
2858 // reasons, see bug 34907. Note that these modules should be loaded from
2859 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2860 // properly use them as dependencies (bug 30914)
2861 if ( $group === 'private' ) {
2862 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2863 $links['html'][] = Html
::inlineStyle(
2864 $resourceLoader->makeModuleResponse( $context, $grpModules )
2867 $links['html'][] = ResourceLoader
::makeInlineScript(
2868 $resourceLoader->makeModuleResponse( $context, $grpModules )
2874 // Special handling for the user group; because users might change their stuff
2875 // on-wiki like user pages, or user preferences; we need to find the highest
2876 // timestamp of these user-changeable modules so we can ensure cache misses on change
2877 // This should NOT be done for the site group (bug 27564) because anons get that too
2878 // and we shouldn't be putting timestamps in CDN-cached HTML
2880 if ( $group === 'user' ) {
2881 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2884 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2885 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2886 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2888 // Automatically select style/script elements
2889 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2890 $link = Html
::linkedStyle( $url );
2892 if ( $context->getRaw() ||
$isRaw ) {
2893 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2894 $link = Html
::element( 'script', [
2895 // In SpecialJavaScriptTest, QUnit must load synchronous
2896 'async' => !isset( $extraQuery['sync'] ),
2900 $link = ResourceLoader
::makeInlineScript(
2901 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
2905 // For modules requested directly in the html via <script> or mw.loader.load
2906 // tell mw.loader they are being loading to prevent duplicate requests.
2907 foreach ( $grpModules as $key => $module ) {
2908 // Don't output state=loading for the startup module.
2909 if ( $key !== 'startup' ) {
2910 $links['states'][$key] = 'loading';
2915 if ( $group == 'noscript' ) {
2916 $links['html'][] = Html
::rawElement( 'noscript', [], $link );
2918 $links['html'][] = $link;
2927 * Build html output from an array of links from makeResourceLoaderLink.
2928 * @param array $links
2929 * @return string|WrappedStringList HTML
2931 protected static function getHtmlFromLoaderLinks( array $links ) {
2934 foreach ( $links as $link ) {
2935 if ( !is_array( $link ) ) {
2938 $html = array_merge( $html, $link['html'] );
2939 $states +
= $link['states'];
2942 // Filter out empty values
2943 $html = array_filter( $html, 'strlen' );
2946 array_unshift( $html, ResourceLoader
::makeInlineScript(
2947 ResourceLoader
::makeLoaderStateScript( $states )
2951 return WrappedString
::join( "\n", $html );
2955 * JS stuff to put in the "<head>". This is the startup module, config
2956 * vars and modules marked with position 'top'
2958 * @return string HTML fragment
2960 function getHeadScripts() {
2961 return $this->getInlineHeadScripts() . $this->getExternalHeadScripts();
2965 * <script src="..."> tags for "<head>".This is the startup module
2966 * and other modules marked with position 'top'.
2968 * @return string|WrappedStringList HTML
2970 function getExternalHeadScripts() {
2971 // Startup - this provides the client with the module
2972 // manifest and loads jquery and mediawiki base modules
2974 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
2975 return self
::getHtmlFromLoaderLinks( $links );
2979 * Inline "<script>" tags to put in "<head>".
2981 * @return string|WrappedStringList HTML
2983 function getInlineHeadScripts() {
2986 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
2987 // Must be done synchronously on every page to avoid flashes of wrong content.
2988 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
2989 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
2990 // For the performance benefit of the majority, this is added unconditionally here and is
2991 // then fixed up by the startup module for unsupported browsers.
2992 $links[] = Html
::inlineScript(
2993 'document.documentElement.className = document.documentElement.className'
2994 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
2997 // Load config before anything else
2998 $links[] = ResourceLoader
::makeInlineScript(
2999 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
3002 // Load embeddable private modules before any loader links
3003 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3004 // in mw.loader.implement() calls and deferred until mw.user is available
3005 $embedScripts = [ 'user.options' ];
3006 $links[] = $this->makeResourceLoaderLink(
3008 ResourceLoaderModule
::TYPE_COMBINED
3010 // Separate user.tokens as otherwise caching will be allowed (T84960)
3011 $links[] = $this->makeResourceLoaderLink(
3013 ResourceLoaderModule
::TYPE_COMBINED
3016 // Modules requests - let the client calculate dependencies and batch requests as it likes
3017 // Only load modules that have marked themselves for loading at the top
3018 $modules = $this->getModules( true, 'top' );
3020 $links[] = ResourceLoader
::makeInlineScript(
3021 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
3025 // "Scripts only" modules marked for top inclusion
3026 $links[] = $this->makeResourceLoaderLink(
3027 $this->getModuleScripts( true, 'top' ),
3028 ResourceLoaderModule
::TYPE_SCRIPTS
3031 return self
::getHtmlFromLoaderLinks( $links );
3035 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3036 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3037 * site JS, and user JS.
3039 * @param bool $unused Previously used to let this method change its output based
3040 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3041 * @return string|WrappedStringList HTML
3043 function getScriptsForBottomQueue( $unused = null ) {
3044 // Scripts "only" requests marked for bottom inclusion
3045 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3048 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3049 ResourceLoaderModule
::TYPE_SCRIPTS
3052 // Modules requests - let the client calculate dependencies and batch requests as it likes
3053 // Only load modules that have marked themselves for loading at the bottom
3054 $modules = $this->getModules( true, 'bottom' );
3056 $links[] = ResourceLoader
::makeInlineScript(
3057 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
3062 $links[] = $this->mScripts
;
3064 // Add user JS if enabled
3065 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3066 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3067 if ( $this->getConfig()->get( 'AllowUserJs' )
3068 && $this->getUser()->isLoggedIn()
3069 && $this->getTitle()
3070 && $this->getTitle()->isJsSubpage()
3071 && $this->userCanPreview()
3073 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3074 // and include the draft contents as a raw script instead.
3075 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3076 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3078 // Load the previewed JS
3079 $links[] = ResourceLoader
::makeInlineScript(
3080 Xml
::encodeJsCall( 'mw.loader.using', [
3084 . Xml
::encodeJsCall( '$.globalEval', [
3085 $this->getRequest()->getText( 'wpTextbox1' )
3092 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3093 // asynchronously and may arrive *after* the inline script here. So the previewed code
3094 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3095 // Similarly, when previewing ./common.js and the user module does arrive first,
3096 // it will arrive without common.js and the inline script runs after.
3097 // Thus running common after the excluded subpage.
3099 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3100 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3103 return self
::getHtmlFromLoaderLinks( $links );
3107 * JS stuff to put at the bottom of the "<body>"
3110 function getBottomScripts() {
3111 return $this->getScriptsForBottomQueue();
3115 * Get the javascript config vars to include on this page
3117 * @return array Array of javascript config vars
3120 public function getJsConfigVars() {
3121 return $this->mJsConfigVars
;
3125 * Add one or more variables to be set in mw.config in JavaScript
3127 * @param string|array $keys Key or array of key/value pairs
3128 * @param mixed $value [optional] Value of the configuration variable
3130 public function addJsConfigVars( $keys, $value = null ) {
3131 if ( is_array( $keys ) ) {
3132 foreach ( $keys as $key => $value ) {
3133 $this->mJsConfigVars
[$key] = $value;
3138 $this->mJsConfigVars
[$keys] = $value;
3142 * Get an array containing the variables to be set in mw.config in JavaScript.
3144 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3145 * - in other words, page-independent/site-wide variables (without state).
3146 * You will only be adding bloat to the html page and causing page caches to
3147 * have to be purged on configuration changes.
3150 public function getJSVars() {
3155 $canonicalSpecialPageName = false; # bug 21115
3157 $title = $this->getTitle();
3158 $ns = $title->getNamespace();
3159 $canonicalNamespace = MWNamespace
::exists( $ns )
3160 ? MWNamespace
::getCanonicalName( $ns )
3161 : $title->getNsText();
3163 $sk = $this->getSkin();
3164 // Get the relevant title so that AJAX features can use the correct page name
3165 // when making API requests from certain special pages (bug 34972).
3166 $relevantTitle = $sk->getRelevantTitle();
3167 $relevantUser = $sk->getRelevantUser();
3169 if ( $ns == NS_SPECIAL
) {
3170 list( $canonicalSpecialPageName, /*...*/ ) =
3171 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3172 } elseif ( $this->canUseWikiPage() ) {
3173 $wikiPage = $this->getWikiPage();
3174 $curRevisionId = $wikiPage->getLatest();
3175 $articleId = $wikiPage->getId();
3178 $lang = $title->getPageViewLanguage();
3180 // Pre-process information
3181 $separatorTransTable = $lang->separatorTransformTable();
3182 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3183 $compactSeparatorTransTable = [
3184 implode( "\t", array_keys( $separatorTransTable ) ),
3185 implode( "\t", $separatorTransTable ),
3187 $digitTransTable = $lang->digitTransformTable();
3188 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3189 $compactDigitTransTable = [
3190 implode( "\t", array_keys( $digitTransTable ) ),
3191 implode( "\t", $digitTransTable ),
3194 $user = $this->getUser();
3197 'wgCanonicalNamespace' => $canonicalNamespace,
3198 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3199 'wgNamespaceNumber' => $title->getNamespace(),
3200 'wgPageName' => $title->getPrefixedDBkey(),
3201 'wgTitle' => $title->getText(),
3202 'wgCurRevisionId' => $curRevisionId,
3203 'wgRevisionId' => (int)$this->getRevisionId(),
3204 'wgArticleId' => $articleId,
3205 'wgIsArticle' => $this->isArticle(),
3206 'wgIsRedirect' => $title->isRedirect(),
3207 'wgAction' => Action
::getActionName( $this->getContext() ),
3208 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3209 'wgUserGroups' => $user->getEffectiveGroups(),
3210 'wgCategories' => $this->getCategories(),
3211 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3212 'wgPageContentLanguage' => $lang->getCode(),
3213 'wgPageContentModel' => $title->getContentModel(),
3214 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3215 'wgDigitTransformTable' => $compactDigitTransTable,
3216 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3217 'wgMonthNames' => $lang->getMonthNamesArray(),
3218 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3219 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3220 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3221 'wgRequestId' => WebRequest
::getRequestId(),
3224 if ( $user->isLoggedIn() ) {
3225 $vars['wgUserId'] = $user->getId();
3226 $vars['wgUserEditCount'] = $user->getEditCount();
3227 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3228 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3229 // Get the revision ID of the oldest new message on the user's talk
3230 // page. This can be used for constructing new message alerts on
3232 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3235 if ( $wgContLang->hasVariants() ) {
3236 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3238 // Same test as SkinTemplate
3239 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3240 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3242 foreach ( $title->getRestrictionTypes() as $type ) {
3243 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3246 if ( $title->isMainPage() ) {
3247 $vars['wgIsMainPage'] = true;
3250 if ( $this->mRedirectedFrom
) {
3251 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3254 if ( $relevantUser ) {
3255 $vars['wgRelevantUserName'] = $relevantUser->getName();
3258 // Allow extensions to add their custom variables to the mw.config map.
3259 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3260 // page-dependant but site-wide (without state).
3261 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3262 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3264 // Merge in variables from addJsConfigVars last
3265 return array_merge( $vars, $this->getJsConfigVars() );
3269 * To make it harder for someone to slip a user a fake
3270 * user-JavaScript or user-CSS preview, a random token
3271 * is associated with the login session. If it's not
3272 * passed back with the preview request, we won't render
3277 public function userCanPreview() {
3278 $request = $this->getRequest();
3280 $request->getVal( 'action' ) !== 'submit' ||
3281 !$request->getCheck( 'wpPreview' ) ||
3282 !$request->wasPosted()
3287 $user = $this->getUser();
3288 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3292 $title = $this->getTitle();
3293 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3296 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3297 // Don't execute another user's CSS or JS on preview (T85855)
3301 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3302 if ( count( $errors ) !== 0 ) {
3310 * @return array Array in format "link name or number => 'link html'".
3312 public function getHeadLinksArray() {
3316 $config = $this->getConfig();
3318 $canonicalUrl = $this->mCanonicalUrl
;
3320 $tags['meta-generator'] = Html
::element( 'meta', [
3321 'name' => 'generator',
3322 'content' => "MediaWiki $wgVersion",
3325 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3326 $tags['meta-referrer'] = Html
::element( 'meta', [
3327 'name' => 'referrer',
3328 'content' => $config->get( 'ReferrerPolicy' )
3332 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3333 if ( $p !== 'index,follow' ) {
3334 // http://www.robotstxt.org/wc/meta-user.html
3335 // Only show if it's different from the default robots policy
3336 $tags['meta-robots'] = Html
::element( 'meta', [
3342 foreach ( $this->mMetatags
as $tag ) {
3343 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3345 $tag[0] = substr( $tag[0], 5 );
3349 $tagName = "meta-{$tag[0]}";
3350 if ( isset( $tags[$tagName] ) ) {
3351 $tagName .= $tag[1];
3353 $tags[$tagName] = Html
::element( 'meta',
3356 'content' => $tag[1]
3361 foreach ( $this->mLinktags
as $tag ) {
3362 $tags[] = Html
::element( 'link', $tag );
3365 # Universal edit button
3366 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3367 $user = $this->getUser();
3368 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3369 && ( $this->getTitle()->exists() ||
3370 $this->getTitle()->quickUserCan( 'create', $user ) )
3372 // Original UniversalEditButton
3373 $msg = $this->msg( 'edit' )->text();
3374 $tags['universal-edit-button'] = Html
::element( 'link', [
3375 'rel' => 'alternate',
3376 'type' => 'application/x-wiki',
3378 'href' => $this->getTitle()->getEditURL(),
3380 // Alternate edit link
3381 $tags['alternative-edit'] = Html
::element( 'link', [
3384 'href' => $this->getTitle()->getEditURL(),
3389 # Generally the order of the favicon and apple-touch-icon links
3390 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3391 # uses whichever one appears later in the HTML source. Make sure
3392 # apple-touch-icon is specified first to avoid this.
3393 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3394 $tags['apple-touch-icon'] = Html
::element( 'link', [
3395 'rel' => 'apple-touch-icon',
3396 'href' => $config->get( 'AppleTouchIcon' )
3400 if ( $config->get( 'Favicon' ) !== false ) {
3401 $tags['favicon'] = Html
::element( 'link', [
3402 'rel' => 'shortcut icon',
3403 'href' => $config->get( 'Favicon' )
3407 # OpenSearch description link
3408 $tags['opensearch'] = Html
::element( 'link', [
3410 'type' => 'application/opensearchdescription+xml',
3411 'href' => wfScript( 'opensearch_desc' ),
3412 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3415 if ( $config->get( 'EnableAPI' ) ) {
3416 # Real Simple Discovery link, provides auto-discovery information
3417 # for the MediaWiki API (and potentially additional custom API
3418 # support such as WordPress or Twitter-compatible APIs for a
3419 # blogging extension, etc)
3420 $tags['rsd'] = Html
::element( 'link', [
3422 'type' => 'application/rsd+xml',
3423 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3424 // Whether RSD accepts relative or protocol-relative URLs is completely
3425 // undocumented, though.
3426 'href' => wfExpandUrl( wfAppendQuery(
3428 [ 'action' => 'rsd' ] ),
3435 if ( !$config->get( 'DisableLangConversion' ) ) {
3436 $lang = $this->getTitle()->getPageLanguage();
3437 if ( $lang->hasVariants() ) {
3438 $variants = $lang->getVariants();
3439 foreach ( $variants as $variant ) {
3440 $tags["variant-$variant"] = Html
::element( 'link', [
3441 'rel' => 'alternate',
3442 'hreflang' => wfBCP47( $variant ),
3443 'href' => $this->getTitle()->getLocalURL(
3444 [ 'variant' => $variant ] )
3448 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3449 $tags["variant-x-default"] = Html
::element( 'link', [
3450 'rel' => 'alternate',
3451 'hreflang' => 'x-default',
3452 'href' => $this->getTitle()->getLocalURL() ] );
3457 if ( $this->copyrightUrl
!== null ) {
3458 $copyright = $this->copyrightUrl
;
3461 if ( $config->get( 'RightsPage' ) ) {
3462 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3465 $copyright = $copy->getLocalURL();
3469 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3470 $copyright = $config->get( 'RightsUrl' );
3475 $tags['copyright'] = Html
::element( 'link', [
3476 'rel' => 'copyright',
3477 'href' => $copyright ]
3482 if ( $config->get( 'Feed' ) ) {
3485 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3486 # Use the page name for the title. In principle, this could
3487 # lead to issues with having the same name for different feeds
3488 # corresponding to the same page, but we can't avoid that at
3491 $feedLinks[] = $this->feedLink(
3494 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3496 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3501 # Recent changes feed should appear on every page (except recentchanges,
3502 # that would be redundant). Put it after the per-page feed to avoid
3503 # changing existing behavior. It's still available, probably via a
3504 # menu in your browser. Some sites might have a different feed they'd
3505 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3506 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3507 # If so, use it instead.
3508 $sitename = $config->get( 'Sitename' );
3509 if ( $config->get( 'OverrideSiteFeed' ) ) {
3510 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3511 // Note, this->feedLink escapes the url.
3512 $feedLinks[] = $this->feedLink(
3515 $this->msg( "site-{$type}-feed", $sitename )->text()
3518 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3519 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3520 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3521 $feedLinks[] = $this->feedLink(
3523 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3524 # For grep: 'site-rss-feed', 'site-atom-feed'
3525 $this->msg( "site-{$format}-feed", $sitename )->text()
3530 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3531 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3532 # use OutputPage::addFeedLink() instead.
3533 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3535 $tags +
= $feedLinks;
3539 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3540 if ( $canonicalUrl !== false ) {
3541 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3543 if ( $this->isArticleRelated() ) {
3544 // This affects all requests where "setArticleRelated" is true. This is
3545 // typically all requests that show content (query title, curid, oldid, diff),
3546 // and all wikipage actions (edit, delete, purge, info, history etc.).
3547 // It does not apply to File pages and Special pages.
3548 // 'history' and 'info' actions address page metadata rather than the page
3549 // content itself, so they may not be canonicalized to the view page url.
3550 // TODO: this ought to be better encapsulated in the Action class.
3551 $action = Action
::getActionName( $this->getContext() );
3552 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3553 $query = "action={$action}";
3557 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3559 $reqUrl = $this->getRequest()->getRequestURL();
3560 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3564 if ( $canonicalUrl !== false ) {
3565 $tags[] = Html
::element( 'link', [
3566 'rel' => 'canonical',
3567 'href' => $canonicalUrl
3575 * @return string HTML tag links to be put in the header.
3576 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3577 * OutputPage::getHeadLinksArray directly.
3579 public function getHeadLinks() {
3580 wfDeprecated( __METHOD__
, '1.24' );
3581 return implode( "\n", $this->getHeadLinksArray() );
3585 * Generate a "<link rel/>" for a feed.
3587 * @param string $type Feed type
3588 * @param string $url URL to the feed
3589 * @param string $text Value of the "title" attribute
3590 * @return string HTML fragment
3592 private function feedLink( $type, $url, $text ) {
3593 return Html
::element( 'link', [
3594 'rel' => 'alternate',
3595 'type' => "application/$type+xml",
3602 * Add a local or specified stylesheet, with the given media options.
3603 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3605 * @param string $style URL to the file
3606 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3607 * @param string $condition For IE conditional comments, specifying an IE version
3608 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3610 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3613 $options['media'] = $media;
3616 $options['condition'] = $condition;
3619 $options['dir'] = $dir;
3621 $this->styles
[$style] = $options;
3625 * Adds inline CSS styles
3626 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3628 * @param mixed $style_css Inline CSS
3629 * @param string $flip Set to 'flip' to flip the CSS if needed
3631 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3632 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3633 # If wanted, and the interface is right-to-left, flip the CSS
3634 $style_css = CSSJanus
::transform( $style_css, true, false );
3636 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3640 * Build a set of "<link>" elements for stylesheets specified in the $this->styles array.
3642 * @return string|WrappedStringList HTML
3644 public function buildCssLinks() {
3647 $this->getSkin()->setupSkinUserCss( $this );
3649 // Add ResourceLoader styles
3650 // Split the styles into these groups
3659 $otherTags = []; // Tags to append after the normal <link> tags
3660 $resourceLoader = $this->getResourceLoader();
3662 $moduleStyles = $this->getModuleStyles();
3664 // Per-site custom styles
3665 $moduleStyles[] = 'site.styles';
3666 $moduleStyles[] = 'noscript';
3668 // Per-user custom styles
3669 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3670 && $this->userCanPreview()
3672 // We're on a preview of a CSS subpage
3673 // Exclude this page from the user module in case it's in there (bug 26283)
3674 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
,
3675 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3677 $otherTags = array_merge( $otherTags, $link['html'] );
3679 // Load the previewed CSS
3680 // If needed, Janus it first. This is user-supplied CSS, so it's
3681 // assumed to be right for the content language directionality.
3682 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3683 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3684 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3686 $otherTags[] = Html
::inlineStyle( $previewedCSS );
3688 // Load the user styles normally
3689 $moduleStyles[] = 'user';
3692 // Per-user preference styles
3693 $moduleStyles[] = 'user.cssprefs';
3695 foreach ( $moduleStyles as $name ) {
3696 $module = $resourceLoader->getModule( $name );
3700 if ( $name === 'site.styles' ) {
3701 // HACK: The site module shouldn't be fragmented with a cache group and
3702 // http request. But in order to ensure its styles are separated and after the
3703 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3704 // The scripts remain ungrouped and rides the bottom queue.
3705 $styles['site'][] = $name;
3708 $group = $module->getGroup();
3709 // Modules in groups other than the ones needing special treatment
3710 // (see $styles assignment)
3711 // will be placed in the "other" style category.
3712 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3715 // We want site, private and user styles to override dynamically added
3716 // styles from modules, but we want dynamically added styles to override
3717 // statically added styles from other modules. So the order has to be
3718 // other, dynamic, site, private, user. Add statically added styles for
3720 $links[] = $this->makeResourceLoaderLink(
3722 ResourceLoaderModule
::TYPE_STYLES
3724 // Add normal styles added through addStyle()/addInlineStyle() here
3725 $links[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3726 // Add marker tag to mark the place where the client-side
3727 // loader should inject dynamic styles
3728 // We use a <meta> tag with a made-up name for this because that's valid HTML
3729 $links[] = Html
::element(
3731 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3734 // Add site-specific and user-specific styles
3735 // 'private' at present only contains user.options, so put that before 'user'
3736 // Any future private modules will likely have a similar user-specific character
3737 foreach ( [ 'site', 'noscript', 'private', 'user' ] as $group ) {
3738 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3739 ResourceLoaderModule
::TYPE_STYLES
3743 // Add stuff in $otherTags (previewed user CSS if applicable)
3744 $links[] = implode( '', $otherTags );
3746 return self
::getHtmlFromLoaderLinks( $links );
3752 public function buildCssLinksArray() {
3755 // Add any extension CSS
3756 foreach ( $this->mExtStyles
as $url ) {
3757 $this->addStyle( $url );
3759 $this->mExtStyles
= [];
3761 foreach ( $this->styles
as $file => $options ) {
3762 $link = $this->styleLink( $file, $options );
3764 $links[$file] = $link;
3771 * Generate \<link\> tags for stylesheets
3773 * @param string $style URL to the file
3774 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3775 * @return string HTML fragment
3777 protected function styleLink( $style, array $options ) {
3778 if ( isset( $options['dir'] ) ) {
3779 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3784 if ( isset( $options['media'] ) ) {
3785 $media = self
::transformCssMedia( $options['media'] );
3786 if ( is_null( $media ) ) {
3793 if ( substr( $style, 0, 1 ) == '/' ||
3794 substr( $style, 0, 5 ) == 'http:' ||
3795 substr( $style, 0, 6 ) == 'https:' ) {
3798 $config = $this->getConfig();
3799 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3800 $config->get( 'StyleVersion' );
3803 $link = Html
::linkedStyle( $url, $media );
3805 if ( isset( $options['condition'] ) ) {
3806 $condition = htmlspecialchars( $options['condition'] );
3807 $link = "<!--[if $condition]>$link<![endif]-->";
3813 * Transform path to web-accessible static resource.
3815 * This is used to add a validation hash as query string.
3816 * This aids various behaviors:
3818 * - Put long Cache-Control max-age headers on responses for improved
3819 * cache performance.
3820 * - Get the correct version of a file as expected by the current page.
3821 * - Instantly get the updated version of a file after deployment.
3823 * Avoid using this for urls included in HTML as otherwise clients may get different
3824 * versions of a resource when navigating the site depending on when the page was cached.
3825 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3826 * an external stylesheet).
3829 * @param Config $config
3830 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3831 * @return string URL
3833 public static function transformResourcePath( Config
$config, $path ) {
3835 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3836 if ( $remotePathPrefix === '' ) {
3837 // The configured base path is required to be empty string for
3838 // wikis in the domain root
3841 $remotePath = $remotePathPrefix;
3843 if ( strpos( $path, $remotePath ) !== 0 ) {
3844 // Path is outside wgResourceBasePath, ignore.
3847 $path = RelPath\
getRelativePath( $path, $remotePath );
3848 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3852 * Utility method for transformResourceFilePath().
3854 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3857 * @param string $remotePath URL path prefix that points to $localPath
3858 * @param string $localPath File directory exposed at $remotePath
3859 * @param string $file Path to target file relative to $localPath
3860 * @return string URL
3862 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3863 $hash = md5_file( "$localPath/$file" );
3864 if ( $hash === false ) {
3865 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3868 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3872 * Transform "media" attribute based on request parameters
3874 * @param string $media Current value of the "media" attribute
3875 * @return string Modified value of the "media" attribute, or null to skip
3878 public static function transformCssMedia( $media ) {
3881 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3882 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3884 // Switch in on-screen display for media testing
3886 'printable' => 'print',
3887 'handheld' => 'handheld',
3889 foreach ( $switches as $switch => $targetMedia ) {
3890 if ( $wgRequest->getBool( $switch ) ) {
3891 if ( $media == $targetMedia ) {
3893 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3894 /* This regex will not attempt to understand a comma-separated media_query_list
3896 * Example supported values for $media:
3897 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3898 * Example NOT supported value for $media:
3899 * '3d-glasses, screen, print and resolution > 90dpi'
3901 * If it's a print request, we never want any kind of screen stylesheets
3902 * If it's a handheld request (currently the only other choice with a switch),
3903 * we don't want simple 'screen' but we might want screen queries that
3904 * have a max-width or something, so we'll pass all others on and let the
3905 * client do the query.
3907 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3918 * Add a wikitext-formatted message to the output.
3919 * This is equivalent to:
3921 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3923 public function addWikiMsg( /*...*/ ) {
3924 $args = func_get_args();
3925 $name = array_shift( $args );
3926 $this->addWikiMsgArray( $name, $args );
3930 * Add a wikitext-formatted message to the output.
3931 * Like addWikiMsg() except the parameters are taken as an array
3932 * instead of a variable argument list.
3934 * @param string $name
3935 * @param array $args
3937 public function addWikiMsgArray( $name, $args ) {
3938 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3942 * This function takes a number of message/argument specifications, wraps them in
3943 * some overall structure, and then parses the result and adds it to the output.
3945 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3946 * and so on. The subsequent arguments may be either
3947 * 1) strings, in which case they are message names, or
3948 * 2) arrays, in which case, within each array, the first element is the message
3949 * name, and subsequent elements are the parameters to that message.
3951 * Don't use this for messages that are not in the user's interface language.
3955 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3959 * $wgOut->addWikiText( "<div class='error'>\n"
3960 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3962 * The newline after the opening div is needed in some wikitext. See bug 19226.
3964 * @param string $wrap
3966 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3967 $msgSpecs = func_get_args();
3968 array_shift( $msgSpecs );
3969 $msgSpecs = array_values( $msgSpecs );
3971 foreach ( $msgSpecs as $n => $spec ) {
3972 if ( is_array( $spec ) ) {
3974 $name = array_shift( $args );
3975 if ( isset( $args['options'] ) ) {
3976 unset( $args['options'] );
3978 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3986 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3988 $this->addWikiText( $s );
3992 * Enables/disables TOC, doesn't override __NOTOC__
3996 public function enableTOC( $flag = true ) {
3997 $this->mEnableTOC
= $flag;
4004 public function isTOCEnabled() {
4005 return $this->mEnableTOC
;
4009 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
4013 public function enableSectionEditLinks( $flag = true ) {
4014 $this->mEnableSectionEditLinks
= $flag;
4021 public function sectionEditLinksEnabled() {
4022 return $this->mEnableSectionEditLinks
;
4026 * Helper function to setup the PHP implementation of OOUI to use in this request.
4029 * @param String $skinName The Skin name to determine the correct OOUI theme
4030 * @param String $dir Language direction
4032 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
4033 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
4034 // Make keys (skin names) lowercase for case-insensitive matching.
4035 $themes = array_change_key_case( $themes, CASE_LOWER
);
4036 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
4037 // For example, 'OOUI\MediaWikiTheme'.
4038 $themeClass = "OOUI\\{$theme}Theme";
4039 OOUI\Theme
::setSingleton( new $themeClass() );
4040 OOUI\Element
::setDefaultDir( $dir );
4044 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4045 * MediaWiki and this OutputPage instance.
4049 public function enableOOUI() {
4051 strtolower( $this->getSkin()->getSkinName() ),
4052 $this->getLanguage()->getDir()
4054 $this->addModuleStyles( [
4055 'oojs-ui-core.styles',
4056 'oojs-ui.styles.icons',
4057 'oojs-ui.styles.indicators',
4058 'oojs-ui.styles.textures',
4059 'mediawiki.widgets.styles',
4061 // Used by 'skipFunction' of the four 'oojs-ui.styles.*' modules. Please don't treat this as a
4062 // public API or you'll be severely disappointed when T87871 is fixed and it disappears.
4063 $this->addMeta( 'X-OOUI-PHP', '1' );