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 WrappedString\WrappedString
;
27 * This class should be covered by a general architecture document which does
28 * not exist as of January 2011. This is one of the Core classes and should
29 * be read at least once by any new developers.
31 * This class is used to prepare the final rendering. A skin is then
32 * applied to the output parameters (links, javascript, html, categories ...).
34 * @todo FIXME: Another class handles sending the whole page to the client.
36 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
41 class OutputPage
extends ContextSource
{
42 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
43 protected $mMetatags = array();
46 protected $mLinktags = array();
49 protected $mCanonicalUrl = false;
52 * @var array Additional stylesheets. Looks like this is for extensions.
53 * Might be replaced by ResourceLoader.
55 protected $mExtStyles = array();
58 * @var string Should be private - has getter and setter. Contains
60 public $mPagetitle = '';
63 * @var string Contains all of the "<body>" content. Should be private we
64 * got set/get accessors and the append() method.
66 public $mBodytext = '';
69 * Holds the debug lines that will be output as comments in page source if
70 * $wgDebugComments is enabled. See also $wgShowDebug.
71 * @deprecated since 1.20; use MWDebug class instead.
73 public $mDebugtext = '';
75 /** @var string Stores contents of "<title>" tag */
76 private $mHTMLtitle = '';
79 * @var bool Is the displayed content related to the source of the
80 * corresponding wiki article.
82 private $mIsarticle = false;
84 /** @var bool Stores "article flag" toggle. */
85 private $mIsArticleRelated = true;
88 * @var bool We have to set isPrintable(). Some pages should
89 * never be printed (ex: redirections).
91 private $mPrintable = false;
94 * @var array Contains the page subtitle. Special pages usually have some
95 * links here. Don't confuse with site subtitle added by skins.
97 private $mSubtitle = array();
100 public $mRedirect = '';
103 protected $mStatusCode;
106 * @var string Variable mLastModified and mEtag are used for sending cache control.
107 * The whole caching system should probably be moved into its own class.
109 protected $mLastModified = '';
112 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
113 * as a unique identifier for the content. It is later used by the client
114 * to compare its cached version with the server version. Client sends
115 * headers If-Match and If-None-Match containing its locally cached ETAG value.
117 * To get more information, you will have to look at HTTP/1.1 protocol which
118 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
120 private $mETag = false;
123 protected $mCategoryLinks = array();
126 protected $mCategories = array();
129 protected $mIndicators = array();
131 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
132 private $mLanguageLinks = array();
135 * Used for JavaScript (predates ResourceLoader)
136 * @todo We should split JS / CSS.
137 * mScripts content is inserted as is in "<head>" by Skin. This might
138 * contain either a link to a stylesheet or inline CSS.
140 private $mScripts = '';
142 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
143 protected $mInlineStyles = '';
146 * @var string Used by skin template.
147 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
149 public $mPageLinkTitle = '';
151 /** @var array Array of elements in "<head>". Parser might add its own headers! */
152 protected $mHeadItems = array();
155 protected $mModules = array();
158 protected $mModuleScripts = array();
161 protected $mModuleStyles = array();
163 /** @var ResourceLoader */
164 protected $mResourceLoader;
167 protected $mJsConfigVars = array();
170 protected $mTemplateIds = array();
173 protected $mImageTimeKeys = array();
176 public $mRedirectCode = '';
178 protected $mFeedLinksAppendQuery = null;
181 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
182 * @see ResourceLoaderModule::$origin
183 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
185 protected $mAllowedModules = array(
186 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
189 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
190 protected $mDoNothing = false;
195 protected $mContainsNewMagic = 0;
198 * lazy initialised, use parserOptions()
201 protected $mParserOptions = null;
204 * Handles the Atom / RSS links.
205 * We probably only support Atom in 2011.
206 * @see $wgAdvertisedFeedTypes
208 private $mFeedLinks = array();
210 // Gwicke work on squid caching? Roughly from 2003.
211 protected $mEnableClientCache = true;
213 /** @var bool Flag if output should only contain the body of the article. */
214 private $mArticleBodyOnly = false;
217 protected $mNewSectionLink = false;
220 protected $mHideNewSectionLink = false;
223 * @var bool Comes from the parser. This was probably made to load CSS/JS
224 * only if we had "<gallery>". Used directly in CategoryPage.php.
225 * Looks like ResourceLoader can replace this.
227 public $mNoGallery = false;
230 private $mPageTitleActionText = '';
232 /** @var int Cache stuff. Looks like mEnableClientCache */
233 protected $mCdnMaxage = 0;
234 /** @var int Upper limit on mCdnMaxage */
235 protected $mCdnMaxageLimit = INF
;
238 * @var bool Controls if anti-clickjacking / frame-breaking headers will
239 * be sent. This should be done for pages where edit actions are possible.
240 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
242 protected $mPreventClickjacking = true;
244 /** @var int To include the variable {{REVISIONID}} */
245 private $mRevisionId = null;
248 private $mRevisionTimestamp = null;
251 protected $mFileVersion = null;
254 * @var array An array of stylesheet filenames (relative from skins path),
255 * with options for CSS media, IE conditions, and RTL/LTR direction.
256 * For internal use; add settings in the skin via $this->addStyle()
258 * Style again! This seems like a code duplication since we already have
259 * mStyles. This is what makes Open Source amazing.
261 protected $styles = array();
264 * Whether jQuery is already handled.
266 protected $mJQueryDone = false;
268 private $mIndexPolicy = 'index';
269 private $mFollowPolicy = 'follow';
270 private $mVaryHeader = array(
271 'Accept-Encoding' => array( 'match=gzip' ),
275 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
280 private $mRedirectedFrom = null;
283 * Additional key => value data
285 private $mProperties = array();
288 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
290 private $mTarget = null;
293 * @var bool Whether parser output should contain table of contents
295 private $mEnableTOC = true;
298 * @var bool Whether parser output should contain section edit links
300 private $mEnableSectionEditLinks = true;
303 * @var string|null The URL to send in a <link> element with rel=copyright
305 private $copyrightUrl;
308 * Constructor for OutputPage. This should not be called directly.
309 * Instead a new RequestContext should be created and it will implicitly create
310 * a OutputPage tied to that context.
311 * @param IContextSource|null $context
313 function __construct( IContextSource
$context = null ) {
314 if ( $context === null ) {
315 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
316 wfDeprecated( __METHOD__
, '1.18' );
318 $this->setContext( $context );
323 * Redirect to $url rather than displaying the normal page
325 * @param string $url URL
326 * @param string $responsecode HTTP status code
328 public function redirect( $url, $responsecode = '302' ) {
329 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
330 $this->mRedirect
= str_replace( "\n", '', $url );
331 $this->mRedirectCode
= $responsecode;
335 * Get the URL to redirect to, or an empty string if not redirect URL set
339 public function getRedirect() {
340 return $this->mRedirect
;
344 * Set the copyright URL to send with the output.
345 * Empty string to omit, null to reset.
349 * @param string|null $url
351 public function setCopyrightUrl( $url ) {
352 $this->copyrightUrl
= $url;
356 * Set the HTTP status code to send with the output.
358 * @param int $statusCode
360 public function setStatusCode( $statusCode ) {
361 $this->mStatusCode
= $statusCode;
365 * Add a new "<meta>" tag
366 * To add an http-equiv meta tag, precede the name with "http:"
368 * @param string $name Tag name
369 * @param string $val Tag value
371 function addMeta( $name, $val ) {
372 array_push( $this->mMetatags
, array( $name, $val ) );
376 * Returns the current <meta> tags
381 public function getMetaTags() {
382 return $this->mMetatags
;
386 * Add a new \<link\> tag to the page header.
388 * Note: use setCanonicalUrl() for rel=canonical.
390 * @param array $linkarr Associative array of attributes.
392 function addLink( array $linkarr ) {
393 array_push( $this->mLinktags
, $linkarr );
397 * Returns the current <link> tags
402 public function getLinkTags() {
403 return $this->mLinktags
;
407 * Add a new \<link\> with "rel" attribute set to "meta"
409 * @param array $linkarr Associative array mapping attribute names to their
410 * values, both keys and values will be escaped, and the
411 * "rel" attribute will be automatically added
413 function addMetadataLink( array $linkarr ) {
414 $linkarr['rel'] = $this->getMetadataAttribute();
415 $this->addLink( $linkarr );
419 * Set the URL to be used for the <link rel=canonical>. This should be used
420 * in preference to addLink(), to avoid duplicate link tags.
423 function setCanonicalUrl( $url ) {
424 $this->mCanonicalUrl
= $url;
428 * Returns the URL to be used for the <link rel=canonical> if
432 * @return bool|string
434 public function getCanonicalUrl() {
435 return $this->mCanonicalUrl
;
439 * Get the value of the "rel" attribute for metadata links
443 public function getMetadataAttribute() {
444 # note: buggy CC software only reads first "meta" link
445 static $haveMeta = false;
447 return 'alternate meta';
455 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
456 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
459 * @param string $script Raw HTML
461 function addScript( $script ) {
462 $this->mScripts
.= $script . "\n";
466 * Register and add a stylesheet from an extension directory.
468 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
469 * @param string $url Path to sheet. Provide either a full url (beginning
470 * with 'http', etc) or a relative path from the document root
471 * (beginning with '/'). Otherwise it behaves identically to
472 * addStyle() and draws from the /skins folder.
474 public function addExtensionStyle( $url ) {
475 wfDeprecated( __METHOD__
, '1.27' );
476 array_push( $this->mExtStyles
, $url );
480 * Get all styles added by extensions
482 * @deprecated since 1.27
485 function getExtStyle() {
486 wfDeprecated( __METHOD__
, '1.27' );
487 return $this->mExtStyles
;
491 * Add a JavaScript file out of skins/common, or a given relative path.
492 * Internal use only. Use OutputPage::addModules() if possible.
494 * @param string $file Filename in skins/common or complete on-server path
496 * @param string $version Style version of the file. Defaults to $wgStyleVersion
498 public function addScriptFile( $file, $version = null ) {
499 // See if $file parameter is an absolute URL or begins with a slash
500 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
503 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
505 if ( is_null( $version ) ) {
506 $version = $this->getConfig()->get( 'StyleVersion' );
508 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
512 * Add a self-contained script tag with the given contents
513 * Internal use only. Use OutputPage::addModules() if possible.
515 * @param string $script JavaScript text, no "<script>" tags
517 public function addInlineScript( $script ) {
518 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
522 * Get all registered JS and CSS tags for the header.
525 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
527 function getScript() {
528 wfDeprecated( __METHOD__
, '1.24' );
529 return $this->mScripts
. $this->getHeadItems();
533 * Filter an array of modules to remove insufficiently trustworthy members, and modules
534 * which are no longer registered (eg a page is cached before an extension is disabled)
535 * @param array $modules
536 * @param string|null $position If not null, only return modules with this position
537 * @param string $type
540 protected function filterModules( array $modules, $position = null,
541 $type = ResourceLoaderModule
::TYPE_COMBINED
543 $resourceLoader = $this->getResourceLoader();
544 $filteredModules = array();
545 foreach ( $modules as $val ) {
546 $module = $resourceLoader->getModule( $val );
547 if ( $module instanceof ResourceLoaderModule
548 && $module->getOrigin() <= $this->getAllowedModules( $type )
549 && ( is_null( $position ) ||
$module->getPosition() == $position )
550 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
552 $filteredModules[] = $val;
555 return $filteredModules;
559 * Get the list of modules to include on this page
561 * @param bool $filter Whether to filter out insufficiently trustworthy modules
562 * @param string|null $position If not null, only return modules with this position
563 * @param string $param
564 * @return array Array of module names
566 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
567 $modules = array_values( array_unique( $this->$param ) );
569 ?
$this->filterModules( $modules, $position )
574 * Add one or more modules recognized by ResourceLoader. Modules added
575 * through this function will be loaded by ResourceLoader when the
578 * @param string|array $modules Module name (string) or array of module names
580 public function addModules( $modules ) {
581 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
585 * Get the list of module JS to include on this page
587 * @param bool $filter
588 * @param string|null $position
590 * @return array Array of module names
592 public function getModuleScripts( $filter = false, $position = null ) {
593 return $this->getModules( $filter, $position, 'mModuleScripts' );
597 * Add only JS of one or more modules recognized by ResourceLoader. Module
598 * scripts added through this function will be loaded by ResourceLoader when
601 * @param string|array $modules Module name (string) or array of module names
603 public function addModuleScripts( $modules ) {
604 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
608 * Get the list of module CSS to include on this page
610 * @param bool $filter
611 * @param string|null $position
613 * @return array Array of module names
615 public function getModuleStyles( $filter = false, $position = null ) {
616 return $this->getModules( $filter, $position, 'mModuleStyles' );
620 * Add only CSS of one or more modules recognized by ResourceLoader.
622 * Module styles added through this function will be added using standard link CSS
623 * tags, rather than as a combined Javascript and CSS package. Thus, they will
624 * load when JavaScript is disabled (unless CSS also happens to be disabled).
626 * @param string|array $modules Module name (string) or array of module names
628 public function addModuleStyles( $modules ) {
629 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
633 * Get the list of module messages to include on this page
635 * @deprecated since 1.26 Obsolete
636 * @param bool $filter
637 * @param string|null $position
638 * @return array Array of module names
640 public function getModuleMessages( $filter = false, $position = null ) {
641 wfDeprecated( __METHOD__
, '1.26' );
646 * Load messages of one or more ResourceLoader modules.
648 * @deprecated since 1.26 Use addModules() instead
649 * @param string|array $modules Module name (string) or array of module names
651 public function addModuleMessages( $modules ) {
652 wfDeprecated( __METHOD__
, '1.26' );
656 * @return null|string ResourceLoader target
658 public function getTarget() {
659 return $this->mTarget
;
663 * Sets ResourceLoader target for load.php links. If null, will be omitted
665 * @param string|null $target
667 public function setTarget( $target ) {
668 $this->mTarget
= $target;
672 * Get an array of head items
676 function getHeadItemsArray() {
677 return $this->mHeadItems
;
681 * Get all header items in a string
684 * @deprecated since 1.24 Use OutputPage::headElement or
685 * if absolutely necessary use OutputPage::getHeadItemsArray
687 function getHeadItems() {
688 wfDeprecated( __METHOD__
, '1.24' );
690 foreach ( $this->mHeadItems
as $item ) {
697 * Add or replace an header item to the output
699 * Whenever possible, use more specific options like ResourceLoader modules,
700 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
701 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
702 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
703 * This would be your very LAST fallback.
705 * @param string $name Item name
706 * @param string $value Raw HTML
708 public function addHeadItem( $name, $value ) {
709 $this->mHeadItems
[$name] = $value;
713 * Check if the header item $name is already set
715 * @param string $name Item name
718 public function hasHeadItem( $name ) {
719 return isset( $this->mHeadItems
[$name] );
723 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
725 * @param string $tag Value of "ETag" header
727 function setETag( $tag ) {
732 * Set whether the output should only contain the body of the article,
733 * without any skin, sidebar, etc.
734 * Used e.g. when calling with "action=render".
736 * @param bool $only Whether to output only the body of the article
738 public function setArticleBodyOnly( $only ) {
739 $this->mArticleBodyOnly
= $only;
743 * Return whether the output will contain only the body of the article
747 public function getArticleBodyOnly() {
748 return $this->mArticleBodyOnly
;
752 * Set an additional output property
755 * @param string $name
756 * @param mixed $value
758 public function setProperty( $name, $value ) {
759 $this->mProperties
[$name] = $value;
763 * Get an additional output property
766 * @param string $name
767 * @return mixed Property value or null if not found
769 public function getProperty( $name ) {
770 if ( isset( $this->mProperties
[$name] ) ) {
771 return $this->mProperties
[$name];
778 * checkLastModified tells the client to use the client-cached page if
779 * possible. If successful, the OutputPage is disabled so that
780 * any future call to OutputPage->output() have no effect.
782 * Side effect: sets mLastModified for Last-Modified header
784 * @param string $timestamp
786 * @return bool True if cache-ok headers was sent.
788 public function checkLastModified( $timestamp ) {
789 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
790 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
793 $config = $this->getConfig();
794 if ( !$config->get( 'CachePages' ) ) {
795 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
799 $timestamp = wfTimestamp( TS_MW
, $timestamp );
800 $modifiedTimes = array(
801 'page' => $timestamp,
802 'user' => $this->getUser()->getTouched(),
803 'epoch' => $config->get( 'CacheEpoch' )
805 if ( $config->get( 'UseSquid' ) ) {
806 // bug 44570: the core page itself may not change, but resources might
807 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
809 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
811 $maxModified = max( $modifiedTimes );
812 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
814 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
815 if ( $clientHeader === false ) {
816 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
820 # IE sends sizes after the date like this:
821 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
822 # this breaks strtotime().
823 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
825 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
826 $clientHeaderTime = strtotime( $clientHeader );
827 MediaWiki\restoreWarnings
();
828 if ( !$clientHeaderTime ) {
830 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
833 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
837 foreach ( $modifiedTimes as $name => $value ) {
838 if ( $info !== '' ) {
841 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
844 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
845 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
846 wfDebug( __METHOD__
. ": effective Last-Modified: " .
847 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
848 if ( $clientHeaderTime < $maxModified ) {
849 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
854 # Give a 304 Not Modified response code and disable body output
855 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
856 ini_set( 'zlib.output_compression', 0 );
857 $this->getRequest()->response()->statusHeader( 304 );
858 $this->sendCacheControl();
861 // Don't output a compressed blob when using ob_gzhandler;
862 // it's technically against HTTP spec and seems to confuse
863 // Firefox when the response gets split over two packets.
864 wfClearOutputBuffers();
870 * Override the last modified timestamp
872 * @param string $timestamp New timestamp, in a format readable by
875 public function setLastModified( $timestamp ) {
876 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
880 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
882 * @param string $policy The literal string to output as the contents of
883 * the meta tag. Will be parsed according to the spec and output in
887 public function setRobotPolicy( $policy ) {
888 $policy = Article
::formatRobotPolicy( $policy );
890 if ( isset( $policy['index'] ) ) {
891 $this->setIndexPolicy( $policy['index'] );
893 if ( isset( $policy['follow'] ) ) {
894 $this->setFollowPolicy( $policy['follow'] );
899 * Set the index policy for the page, but leave the follow policy un-
902 * @param string $policy Either 'index' or 'noindex'.
905 public function setIndexPolicy( $policy ) {
906 $policy = trim( $policy );
907 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
908 $this->mIndexPolicy
= $policy;
913 * Set the follow policy for the page, but leave the index policy un-
916 * @param string $policy Either 'follow' or 'nofollow'.
919 public function setFollowPolicy( $policy ) {
920 $policy = trim( $policy );
921 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
922 $this->mFollowPolicy
= $policy;
927 * Set the new value of the "action text", this will be added to the
928 * "HTML title", separated from it with " - ".
930 * @param string $text New value of the "action text"
932 public function setPageTitleActionText( $text ) {
933 $this->mPageTitleActionText
= $text;
937 * Get the value of the "action text"
941 public function getPageTitleActionText() {
942 return $this->mPageTitleActionText
;
946 * "HTML title" means the contents of "<title>".
947 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
949 * @param string|Message $name
951 public function setHTMLTitle( $name ) {
952 if ( $name instanceof Message
) {
953 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
955 $this->mHTMLtitle
= $name;
960 * Return the "HTML title", i.e. the content of the "<title>" tag.
964 public function getHTMLTitle() {
965 return $this->mHTMLtitle
;
969 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
973 public function setRedirectedFrom( $t ) {
974 $this->mRedirectedFrom
= $t;
978 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
979 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
980 * but not bad tags like \<script\>. This function automatically sets
981 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
982 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
983 * good tags like \<i\> will be dropped entirely.
985 * @param string|Message $name
987 public function setPageTitle( $name ) {
988 if ( $name instanceof Message
) {
989 $name = $name->setContext( $this->getContext() )->text();
992 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
993 # but leave "<i>foobar</i>" alone
994 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
995 $this->mPagetitle
= $nameWithTags;
997 # change "<i>foo&bar</i>" to "foo&bar"
999 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
1000 ->inContentLanguage()
1005 * Return the "page title", i.e. the content of the \<h1\> tag.
1009 public function getPageTitle() {
1010 return $this->mPagetitle
;
1014 * Set the Title object to use
1018 public function setTitle( Title
$t ) {
1019 $this->getContext()->setTitle( $t );
1023 * Replace the subtitle with $str
1025 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1027 public function setSubtitle( $str ) {
1028 $this->clearSubtitle();
1029 $this->addSubtitle( $str );
1033 * Add $str to the subtitle
1035 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1037 public function addSubtitle( $str ) {
1038 if ( $str instanceof Message
) {
1039 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1041 $this->mSubtitle
[] = $str;
1046 * Build message object for a subtitle containing a backlink to a page
1048 * @param Title $title Title to link to
1049 * @param array $query Array of additional parameters to include in the link
1053 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1054 if ( $title->isRedirect() ) {
1055 $query['redirect'] = 'no';
1057 return wfMessage( 'backlinksubtitle' )
1058 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1062 * Add a subtitle containing a backlink to a page
1064 * @param Title $title Title to link to
1065 * @param array $query Array of additional parameters to include in the link
1067 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1068 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1072 * Clear the subtitles
1074 public function clearSubtitle() {
1075 $this->mSubtitle
= array();
1083 public function getSubtitle() {
1084 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1088 * Set the page as printable, i.e. it'll be displayed with all
1089 * print styles included
1091 public function setPrintable() {
1092 $this->mPrintable
= true;
1096 * Return whether the page is "printable"
1100 public function isPrintable() {
1101 return $this->mPrintable
;
1105 * Disable output completely, i.e. calling output() will have no effect
1107 public function disable() {
1108 $this->mDoNothing
= true;
1112 * Return whether the output will be completely disabled
1116 public function isDisabled() {
1117 return $this->mDoNothing
;
1121 * Show an "add new section" link?
1125 public function showNewSectionLink() {
1126 return $this->mNewSectionLink
;
1130 * Forcibly hide the new section link?
1134 public function forceHideNewSectionLink() {
1135 return $this->mHideNewSectionLink
;
1139 * Add or remove feed links in the page header
1140 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1141 * for the new version
1142 * @see addFeedLink()
1144 * @param bool $show True: add default feeds, false: remove all feeds
1146 public function setSyndicated( $show = true ) {
1148 $this->setFeedAppendQuery( false );
1150 $this->mFeedLinks
= array();
1155 * Add default feeds to the page header
1156 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1157 * for the new version
1158 * @see addFeedLink()
1160 * @param string $val Query to append to feed links or false to output
1163 public function setFeedAppendQuery( $val ) {
1164 $this->mFeedLinks
= array();
1166 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1167 $query = "feed=$type";
1168 if ( is_string( $val ) ) {
1169 $query .= '&' . $val;
1171 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1176 * Add a feed link to the page header
1178 * @param string $format Feed type, should be a key of $wgFeedClasses
1179 * @param string $href URL
1181 public function addFeedLink( $format, $href ) {
1182 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1183 $this->mFeedLinks
[$format] = $href;
1188 * Should we output feed links for this page?
1191 public function isSyndicated() {
1192 return count( $this->mFeedLinks
) > 0;
1196 * Return URLs for each supported syndication format for this page.
1197 * @return array Associating format keys with URLs
1199 public function getSyndicationLinks() {
1200 return $this->mFeedLinks
;
1204 * Will currently always return null
1208 public function getFeedAppendQuery() {
1209 return $this->mFeedLinksAppendQuery
;
1213 * Set whether the displayed content is related to the source of the
1214 * corresponding article on the wiki
1215 * Setting true will cause the change "article related" toggle to true
1219 public function setArticleFlag( $v ) {
1220 $this->mIsarticle
= $v;
1222 $this->mIsArticleRelated
= $v;
1227 * Return whether the content displayed page is related to the source of
1228 * the corresponding article on the wiki
1232 public function isArticle() {
1233 return $this->mIsarticle
;
1237 * Set whether this page is related an article on the wiki
1238 * Setting false will cause the change of "article flag" toggle to false
1242 public function setArticleRelated( $v ) {
1243 $this->mIsArticleRelated
= $v;
1245 $this->mIsarticle
= false;
1250 * Return whether this page is related an article on the wiki
1254 public function isArticleRelated() {
1255 return $this->mIsArticleRelated
;
1259 * Add new language links
1261 * @param array $newLinkArray Associative array mapping language code to the page
1264 public function addLanguageLinks( array $newLinkArray ) {
1265 $this->mLanguageLinks +
= $newLinkArray;
1269 * Reset the language links and add new language links
1271 * @param array $newLinkArray Associative array mapping language code to the page
1274 public function setLanguageLinks( array $newLinkArray ) {
1275 $this->mLanguageLinks
= $newLinkArray;
1279 * Get the list of language links
1281 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1283 public function getLanguageLinks() {
1284 return $this->mLanguageLinks
;
1288 * Add an array of categories, with names in the keys
1290 * @param array $categories Mapping category name => sort key
1292 public function addCategoryLinks( array $categories ) {
1295 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1299 # Add the links to a LinkBatch
1300 $arr = array( NS_CATEGORY
=> $categories );
1301 $lb = new LinkBatch
;
1302 $lb->setArray( $arr );
1304 # Fetch existence plus the hiddencat property
1305 $dbr = wfGetDB( DB_SLAVE
);
1306 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1307 'page_is_redirect', 'page_latest', 'pp_value' );
1309 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1310 $fields[] = 'page_content_model';
1313 $res = $dbr->select( array( 'page', 'page_props' ),
1315 $lb->constructSet( 'page', $dbr ),
1318 array( 'page_props' => array( 'LEFT JOIN', array(
1319 'pp_propname' => 'hiddencat',
1324 # Add the results to the link cache
1325 $lb->addResultToCache( LinkCache
::singleton(), $res );
1327 # Set all the values to 'normal'.
1328 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1330 # Mark hidden categories
1331 foreach ( $res as $row ) {
1332 if ( isset( $row->pp_value
) ) {
1333 $categories[$row->page_title
] = 'hidden';
1337 # Add the remaining categories to the skin
1339 'OutputPageMakeCategoryLinks',
1340 array( &$this, $categories, &$this->mCategoryLinks
) )
1342 foreach ( $categories as $category => $type ) {
1343 // array keys will cast numeric category names to ints, so cast back to string
1344 $category = (string)$category;
1345 $origcategory = $category;
1346 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1350 $wgContLang->findVariantLink( $category, $title, true );
1351 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1354 $text = $wgContLang->convertHtml( $title->getText() );
1355 $this->mCategories
[] = $title->getText();
1356 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1362 * Reset the category links (but not the category list) and add $categories
1364 * @param array $categories Mapping category name => sort key
1366 public function setCategoryLinks( array $categories ) {
1367 $this->mCategoryLinks
= array();
1368 $this->addCategoryLinks( $categories );
1372 * Get the list of category links, in a 2-D array with the following format:
1373 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1374 * hidden categories) and $link a HTML fragment with a link to the category
1379 public function getCategoryLinks() {
1380 return $this->mCategoryLinks
;
1384 * Get the list of category names this page belongs to
1386 * @return array Array of strings
1388 public function getCategories() {
1389 return $this->mCategories
;
1393 * Add an array of indicators, with their identifiers as array
1394 * keys and HTML contents as values.
1396 * In case of duplicate keys, existing values are overwritten.
1398 * @param array $indicators
1401 public function setIndicators( array $indicators ) {
1402 $this->mIndicators
= $indicators +
$this->mIndicators
;
1403 // Keep ordered by key
1404 ksort( $this->mIndicators
);
1408 * Get the indicators associated with this page.
1410 * The array will be internally ordered by item keys.
1412 * @return array Keys: identifiers, values: HTML contents
1415 public function getIndicators() {
1416 return $this->mIndicators
;
1420 * Adds help link with an icon via page indicators.
1421 * Link target can be overridden by a local message containing a wikilink:
1422 * the message key is: lowercase action or special page name + '-helppage'.
1423 * @param string $to Target MediaWiki.org page title or encoded URL.
1424 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1427 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1428 $this->addModuleStyles( 'mediawiki.helplink' );
1429 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1431 if ( $overrideBaseUrl ) {
1434 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1435 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1438 $link = Html
::rawElement(
1442 'target' => '_blank',
1443 'class' => 'mw-helplink',
1448 $this->setIndicators( array( 'mw-helplink' => $link ) );
1452 * Do not allow scripts which can be modified by wiki users to load on this page;
1453 * only allow scripts bundled with, or generated by, the software.
1454 * Site-wide styles are controlled by a config setting, since they can be
1455 * used to create a custom skin/theme, but not user-specific ones.
1457 * @todo this should be given a more accurate name
1459 public function disallowUserJs() {
1460 $this->reduceAllowedModules(
1461 ResourceLoaderModule
::TYPE_SCRIPTS
,
1462 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1465 // Site-wide styles are controlled by a config setting, see bug 71621
1466 // for background on why. User styles are never allowed.
1467 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1468 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1470 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1472 $this->reduceAllowedModules(
1473 ResourceLoaderModule
::TYPE_STYLES
,
1479 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1480 * @see ResourceLoaderModule::$origin
1481 * @param string $type ResourceLoaderModule TYPE_ constant
1482 * @return int ResourceLoaderModule ORIGIN_ class constant
1484 public function getAllowedModules( $type ) {
1485 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1486 return min( array_values( $this->mAllowedModules
) );
1488 return isset( $this->mAllowedModules
[$type] )
1489 ?
$this->mAllowedModules
[$type]
1490 : ResourceLoaderModule
::ORIGIN_ALL
;
1495 * Set the highest level of CSS/JS untrustworthiness allowed
1497 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1498 * Use reduceAllowedModules() instead
1499 * @param string $type ResourceLoaderModule TYPE_ constant
1500 * @param int $level ResourceLoaderModule class constant
1502 public function setAllowedModules( $type, $level ) {
1503 wfDeprecated( __METHOD__
, '1.24' );
1504 $this->reduceAllowedModules( $type, $level );
1508 * Limit the highest level of CSS/JS untrustworthiness allowed.
1510 * If passed the same or a higher level than the current level of untrustworthiness set, the
1511 * level will remain unchanged.
1513 * @param string $type
1514 * @param int $level ResourceLoaderModule class constant
1516 public function reduceAllowedModules( $type, $level ) {
1517 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1521 * Prepend $text to the body HTML
1523 * @param string $text HTML
1525 public function prependHTML( $text ) {
1526 $this->mBodytext
= $text . $this->mBodytext
;
1530 * Append $text to the body HTML
1532 * @param string $text HTML
1534 public function addHTML( $text ) {
1535 $this->mBodytext
.= $text;
1539 * Shortcut for adding an Html::element via addHTML.
1543 * @param string $element
1544 * @param array $attribs
1545 * @param string $contents
1547 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1548 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1552 * Clear the body HTML
1554 public function clearHTML() {
1555 $this->mBodytext
= '';
1561 * @return string HTML
1563 public function getHTML() {
1564 return $this->mBodytext
;
1568 * Get/set the ParserOptions object to use for wikitext parsing
1570 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1571 * current ParserOption object
1572 * @return ParserOptions
1574 public function parserOptions( $options = null ) {
1575 if ( !$this->mParserOptions
) {
1576 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1577 $this->mParserOptions
->setEditSection( false );
1579 return wfSetVar( $this->mParserOptions
, $options );
1583 * Set the revision ID which will be seen by the wiki text parser
1584 * for things such as embedded {{REVISIONID}} variable use.
1586 * @param int|null $revid An positive integer, or null
1587 * @return mixed Previous value
1589 public function setRevisionId( $revid ) {
1590 $val = is_null( $revid ) ?
null : intval( $revid );
1591 return wfSetVar( $this->mRevisionId
, $val );
1595 * Get the displayed revision ID
1599 public function getRevisionId() {
1600 return $this->mRevisionId
;
1604 * Set the timestamp of the revision which will be displayed. This is used
1605 * to avoid a extra DB call in Skin::lastModified().
1607 * @param string|null $timestamp
1608 * @return mixed Previous value
1610 public function setRevisionTimestamp( $timestamp ) {
1611 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1615 * Get the timestamp of displayed revision.
1616 * This will be null if not filled by setRevisionTimestamp().
1618 * @return string|null
1620 public function getRevisionTimestamp() {
1621 return $this->mRevisionTimestamp
;
1625 * Set the displayed file version
1627 * @param File|bool $file
1628 * @return mixed Previous value
1630 public function setFileVersion( $file ) {
1632 if ( $file instanceof File
&& $file->exists() ) {
1633 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1635 return wfSetVar( $this->mFileVersion
, $val, true );
1639 * Get the displayed file version
1641 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1643 public function getFileVersion() {
1644 return $this->mFileVersion
;
1648 * Get the templates used on this page
1650 * @return array (namespace => dbKey => revId)
1653 public function getTemplateIds() {
1654 return $this->mTemplateIds
;
1658 * Get the files used on this page
1660 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1663 public function getFileSearchOptions() {
1664 return $this->mImageTimeKeys
;
1668 * Convert wikitext to HTML and add it to the buffer
1669 * Default assumes that the current page title will be used.
1671 * @param string $text
1672 * @param bool $linestart Is this the start of a line?
1673 * @param bool $interface Is this text in the user interface language?
1674 * @throws MWException
1676 public function addWikiText( $text, $linestart = true, $interface = true ) {
1677 $title = $this->getTitle(); // Work around E_STRICT
1679 throw new MWException( 'Title is null' );
1681 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1685 * Add wikitext with a custom Title object
1687 * @param string $text Wikitext
1688 * @param Title $title
1689 * @param bool $linestart Is this the start of a line?
1691 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1692 $this->addWikiTextTitle( $text, $title, $linestart );
1696 * Add wikitext with a custom Title object and tidy enabled.
1698 * @param string $text Wikitext
1699 * @param Title $title
1700 * @param bool $linestart Is this the start of a line?
1702 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1703 $this->addWikiTextTitle( $text, $title, $linestart, true );
1707 * Add wikitext with tidy enabled
1709 * @param string $text Wikitext
1710 * @param bool $linestart Is this the start of a line?
1712 public function addWikiTextTidy( $text, $linestart = true ) {
1713 $title = $this->getTitle();
1714 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1718 * Add wikitext with a custom Title object
1720 * @param string $text Wikitext
1721 * @param Title $title
1722 * @param bool $linestart Is this the start of a line?
1723 * @param bool $tidy Whether to use tidy
1724 * @param bool $interface Whether it is an interface message
1725 * (for example disables conversion)
1727 public function addWikiTextTitle( $text, Title
$title, $linestart,
1728 $tidy = false, $interface = false
1732 $popts = $this->parserOptions();
1733 $oldTidy = $popts->setTidy( $tidy );
1734 $popts->setInterfaceMessage( (bool)$interface );
1736 $parserOutput = $wgParser->getFreshParser()->parse(
1737 $text, $title, $popts,
1738 $linestart, true, $this->mRevisionId
1741 $popts->setTidy( $oldTidy );
1743 $this->addParserOutput( $parserOutput );
1748 * Add a ParserOutput object, but without Html.
1750 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1751 * @param ParserOutput $parserOutput
1753 public function addParserOutputNoText( $parserOutput ) {
1754 wfDeprecated( __METHOD__
, '1.24' );
1755 $this->addParserOutputMetadata( $parserOutput );
1759 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1760 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1764 * @param ParserOutput $parserOutput
1766 public function addParserOutputMetadata( $parserOutput ) {
1767 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1768 $this->addCategoryLinks( $parserOutput->getCategories() );
1769 $this->setIndicators( $parserOutput->getIndicators() );
1770 $this->mNewSectionLink
= $parserOutput->getNewSection();
1771 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1773 if ( !$parserOutput->isCacheable() ) {
1774 $this->enableClientCache( false );
1776 $this->mNoGallery
= $parserOutput->getNoGallery();
1777 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1778 $this->addModules( $parserOutput->getModules() );
1779 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1780 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1781 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1782 $this->mPreventClickjacking
= $this->mPreventClickjacking
1783 ||
$parserOutput->preventClickjacking();
1785 // Template versioning...
1786 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1787 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1788 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1790 $this->mTemplateIds
[$ns] = $dbks;
1793 // File versioning...
1794 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1795 $this->mImageTimeKeys
[$dbk] = $data;
1798 // Hooks registered in the object
1799 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1800 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1801 list( $hookName, $data ) = $hookInfo;
1802 if ( isset( $parserOutputHooks[$hookName] ) ) {
1803 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1807 // enable OOUI if requested via ParserOutput
1808 if ( $parserOutput->getEnableOOUI() ) {
1809 $this->enableOOUI();
1812 // Link flags are ignored for now, but may in the future be
1813 // used to mark individual language links.
1814 $linkFlags = array();
1815 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1816 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1820 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1821 * ParserOutput object, without any other metadata.
1824 * @param ParserOutput $parserOutput
1826 public function addParserOutputContent( $parserOutput ) {
1827 $this->addParserOutputText( $parserOutput );
1829 $this->addModules( $parserOutput->getModules() );
1830 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1831 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1833 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1837 * Add the HTML associated with a ParserOutput object, without any metadata.
1840 * @param ParserOutput $parserOutput
1842 public function addParserOutputText( $parserOutput ) {
1843 $text = $parserOutput->getText();
1844 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1845 $this->addHTML( $text );
1849 * Add everything from a ParserOutput object.
1851 * @param ParserOutput $parserOutput
1853 function addParserOutput( $parserOutput ) {
1854 $this->addParserOutputMetadata( $parserOutput );
1855 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1857 // Touch section edit links only if not previously disabled
1858 if ( $parserOutput->getEditSectionTokens() ) {
1859 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1862 $this->addParserOutputText( $parserOutput );
1866 * Add the output of a QuickTemplate to the output buffer
1868 * @param QuickTemplate $template
1870 public function addTemplate( &$template ) {
1871 $this->addHTML( $template->getHTML() );
1875 * Parse wikitext and return the HTML.
1877 * @param string $text
1878 * @param bool $linestart Is this the start of a line?
1879 * @param bool $interface Use interface language ($wgLang instead of
1880 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1881 * This also disables LanguageConverter.
1882 * @param Language $language Target language object, will override $interface
1883 * @throws MWException
1884 * @return string HTML
1886 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1889 if ( is_null( $this->getTitle() ) ) {
1890 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1893 $popts = $this->parserOptions();
1895 $popts->setInterfaceMessage( true );
1897 if ( $language !== null ) {
1898 $oldLang = $popts->setTargetLanguage( $language );
1901 $parserOutput = $wgParser->getFreshParser()->parse(
1902 $text, $this->getTitle(), $popts,
1903 $linestart, true, $this->mRevisionId
1907 $popts->setInterfaceMessage( false );
1909 if ( $language !== null ) {
1910 $popts->setTargetLanguage( $oldLang );
1913 return $parserOutput->getText();
1917 * Parse wikitext, strip paragraphs, and return the HTML.
1919 * @param string $text
1920 * @param bool $linestart Is this the start of a line?
1921 * @param bool $interface Use interface language ($wgLang instead of
1922 * $wgContLang) while parsing language sensitive magic
1923 * words like GRAMMAR and PLURAL
1924 * @return string HTML
1926 public function parseInline( $text, $linestart = true, $interface = false ) {
1927 $parsed = $this->parse( $text, $linestart, $interface );
1928 return Parser
::stripOuterParagraph( $parsed );
1933 * @deprecated since 1.27 Use setCdnMaxage() instead
1935 public function setSquidMaxage( $maxage ) {
1936 $this->setCdnMaxage( $maxage );
1940 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1942 * @param int $maxage Maximum cache time on the CDN, in seconds.
1944 public function setCdnMaxage( $maxage ) {
1945 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1949 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1951 * @param int $maxage Maximum cache time on the CDN, in seconds
1954 public function lowerCdnMaxage( $maxage ) {
1955 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1956 $this->setCdnMaxage( $this->mCdnMaxage
);
1960 * Use enableClientCache(false) to force it to send nocache headers
1962 * @param bool $state
1966 public function enableClientCache( $state ) {
1967 return wfSetVar( $this->mEnableClientCache
, $state );
1971 * Get the list of cookies that will influence on the cache
1975 function getCacheVaryCookies() {
1977 if ( $cookies === null ) {
1978 $config = $this->getConfig();
1979 $cookies = array_merge(
1981 $config->get( 'CookiePrefix' ) . 'Token',
1982 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1986 $config->get( 'CacheVaryCookies' )
1988 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1994 * Check if the request has a cache-varying cookie header
1995 * If it does, it's very important that we don't allow public caching
1999 function haveCacheVaryCookies() {
2000 $request = $this->getRequest();
2001 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2002 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2003 wfDebug( __METHOD__
. ": found $cookieName\n" );
2007 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2012 * Add an HTTP header that will influence on the cache
2014 * @param string $header Header name
2015 * @param string[]|null $option Options for the Key header. See
2016 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2017 * for the list of valid options.
2019 public function addVaryHeader( $header, array $option = null ) {
2020 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2021 $this->mVaryHeader
[$header] = array();
2023 if ( !is_array( $option ) ) {
2026 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2030 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2031 * such as Accept-Encoding or Cookie
2035 public function getVaryHeader() {
2036 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
2040 * Get a complete Key header
2044 public function getKeyHeader() {
2045 $cvCookies = $this->getCacheVaryCookies();
2047 $cookiesOption = array();
2048 foreach ( $cvCookies as $cookieName ) {
2049 $cookiesOption[] = 'param=' . $cookieName;
2051 $this->addVaryHeader( 'Cookie', $cookiesOption );
2054 foreach ( $this->mVaryHeader
as $header => $option ) {
2055 $newheader = $header;
2056 if ( is_array( $option ) && count( $option ) > 0 ) {
2057 $newheader .= ';' . implode( ';', $option );
2059 $headers[] = $newheader;
2061 $key = 'Key: ' . implode( ',', $headers );
2067 * T23672: Add Accept-Language to Vary and Key headers
2068 * if there's no 'variant' parameter existed in GET.
2071 * /w/index.php?title=Main_page should always be served; but
2072 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2074 function addAcceptLanguage() {
2075 $title = $this->getTitle();
2076 if ( !$title instanceof Title
) {
2080 $lang = $title->getPageLanguage();
2081 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2082 $variants = $lang->getVariants();
2083 $aloption = array();
2084 foreach ( $variants as $variant ) {
2085 if ( $variant === $lang->getCode() ) {
2088 $aloption[] = 'substr=' . $variant;
2090 // IE and some other browsers use BCP 47 standards in
2091 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2092 // We should handle these too.
2093 $variantBCP47 = wfBCP47( $variant );
2094 if ( $variantBCP47 !== $variant ) {
2095 $aloption[] = 'substr=' . $variantBCP47;
2099 $this->addVaryHeader( 'Accept-Language', $aloption );
2104 * Set a flag which will cause an X-Frame-Options header appropriate for
2105 * edit pages to be sent. The header value is controlled by
2106 * $wgEditPageFrameOptions.
2108 * This is the default for special pages. If you display a CSRF-protected
2109 * form on an ordinary view page, then you need to call this function.
2111 * @param bool $enable
2113 public function preventClickjacking( $enable = true ) {
2114 $this->mPreventClickjacking
= $enable;
2118 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2119 * This can be called from pages which do not contain any CSRF-protected
2122 public function allowClickjacking() {
2123 $this->mPreventClickjacking
= false;
2127 * Get the prevent-clickjacking flag
2132 public function getPreventClickjacking() {
2133 return $this->mPreventClickjacking
;
2137 * Get the X-Frame-Options header value (without the name part), or false
2138 * if there isn't one. This is used by Skin to determine whether to enable
2139 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2143 public function getFrameOptions() {
2144 $config = $this->getConfig();
2145 if ( $config->get( 'BreakFrames' ) ) {
2147 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2148 return $config->get( 'EditPageFrameOptions' );
2154 * Send cache control HTTP headers
2156 public function sendCacheControl() {
2157 $response = $this->getRequest()->response();
2158 $config = $this->getConfig();
2159 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2160 $response->header( "ETag: $this->mETag" );
2163 $this->addVaryHeader( 'Cookie' );
2164 $this->addAcceptLanguage();
2166 # don't serve compressed data to clients who can't handle it
2167 # maintain different caches for logged-in users and non-logged in ones
2168 $response->header( $this->getVaryHeader() );
2170 if ( $config->get( 'UseKeyHeader' ) ) {
2171 $response->header( $this->getKeyHeader() );
2174 if ( $this->mEnableClientCache
) {
2176 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2177 $this->mCdnMaxage
!= 0 && !$this->haveCacheVaryCookies()
2179 if ( $config->get( 'UseESI' ) ) {
2180 # We'll purge the proxy cache explicitly, but require end user agents
2181 # to revalidate against the proxy on each visit.
2182 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2183 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2184 # start with a shorter timeout for initial testing
2185 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2186 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2187 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2188 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2190 # We'll purge the proxy cache for anons explicitly, but require end user agents
2191 # to revalidate against the proxy on each visit.
2192 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2193 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2194 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2195 # start with a shorter timeout for initial testing
2196 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2197 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2198 . ', must-revalidate, max-age=0' );
2201 # We do want clients to cache if they can, but they *must* check for updates
2202 # on revisiting the page.
2203 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2204 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2205 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2207 if ( $this->mLastModified
) {
2208 $response->header( "Last-Modified: {$this->mLastModified}" );
2211 wfDebug( __METHOD__
. ": no caching **", 'private' );
2213 # In general, the absence of a last modified header should be enough to prevent
2214 # the client from using its cache. We send a few other things just to make sure.
2215 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2216 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2217 $response->header( 'Pragma: no-cache' );
2222 * Finally, all the text has been munged and accumulated into
2223 * the object, let's actually output it:
2225 public function output() {
2226 if ( $this->mDoNothing
) {
2230 $response = $this->getRequest()->response();
2231 $config = $this->getConfig();
2233 if ( $this->mRedirect
!= '' ) {
2234 # Standards require redirect URLs to be absolute
2235 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2237 $redirect = $this->mRedirect
;
2238 $code = $this->mRedirectCode
;
2240 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2241 if ( $code == '301' ||
$code == '303' ) {
2242 if ( !$config->get( 'DebugRedirects' ) ) {
2243 $response->statusHeader( $code );
2245 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2247 if ( $config->get( 'VaryOnXFP' ) ) {
2248 $this->addVaryHeader( 'X-Forwarded-Proto' );
2250 $this->sendCacheControl();
2252 $response->header( "Content-Type: text/html; charset=utf-8" );
2253 if ( $config->get( 'DebugRedirects' ) ) {
2254 $url = htmlspecialchars( $redirect );
2255 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2256 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2257 print "</body>\n</html>\n";
2259 $response->header( 'Location: ' . $redirect );
2264 } elseif ( $this->mStatusCode
) {
2265 $response->statusHeader( $this->mStatusCode
);
2268 # Buffer output; final headers may depend on later processing
2271 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2272 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2274 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2275 // jQuery etc. can work correctly.
2276 $response->header( 'X-UA-Compatible: IE=Edge' );
2278 // Prevent framing, if requested
2279 $frameOptions = $this->getFrameOptions();
2280 if ( $frameOptions ) {
2281 $response->header( "X-Frame-Options: $frameOptions" );
2284 if ( $this->mArticleBodyOnly
) {
2285 echo $this->mBodytext
;
2287 $sk = $this->getSkin();
2288 // add skin specific modules
2289 $modules = $sk->getDefaultModules();
2291 // Enforce various default modules for all skins
2292 $coreModules = array(
2293 // Keep this list as small as possible
2295 'mediawiki.page.startup',
2299 // Support for high-density display images if enabled
2300 if ( $config->get( 'ResponsiveImages' ) ) {
2301 $coreModules[] = 'mediawiki.hidpi';
2304 $this->addModules( $coreModules );
2305 foreach ( $modules as $group ) {
2306 $this->addModules( $group );
2308 MWDebug
::addModules( $this );
2310 // Hook that allows last minute changes to the output page, e.g.
2311 // adding of CSS or Javascript by extensions.
2312 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2317 // This hook allows last minute changes to final overall output by modifying output buffer
2318 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2320 $this->sendCacheControl();
2327 * Actually output something with print.
2329 * @param string $ins The string to output
2330 * @deprecated since 1.22 Use echo yourself.
2332 public function out( $ins ) {
2333 wfDeprecated( __METHOD__
, '1.22' );
2338 * Prepare this object to display an error page; disable caching and
2339 * indexing, clear the current text and redirect, set the page's title
2340 * and optionally an custom HTML title (content of the "<title>" tag).
2342 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2343 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2344 * optional, if not passed the "<title>" attribute will be
2345 * based on $pageTitle
2347 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2348 $this->setPageTitle( $pageTitle );
2349 if ( $htmlTitle !== false ) {
2350 $this->setHTMLTitle( $htmlTitle );
2352 $this->setRobotPolicy( 'noindex,nofollow' );
2353 $this->setArticleRelated( false );
2354 $this->enableClientCache( false );
2355 $this->mRedirect
= '';
2356 $this->clearSubtitle();
2361 * Output a standard error page
2363 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2364 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2365 * showErrorPage( 'titlemsg', $messageObject );
2366 * showErrorPage( $titleMessageObject, $messageObject );
2368 * @param string|Message $title Message key (string) for page title, or a Message object
2369 * @param string|Message $msg Message key (string) for page text, or a Message object
2370 * @param array $params Message parameters; ignored if $msg is a Message object
2372 public function showErrorPage( $title, $msg, $params = array() ) {
2373 if ( !$title instanceof Message
) {
2374 $title = $this->msg( $title );
2377 $this->prepareErrorPage( $title );
2379 if ( $msg instanceof Message
) {
2380 if ( $params !== array() ) {
2381 trigger_error( 'Argument ignored: $params. The message parameters argument '
2382 . 'is discarded when the $msg argument is a Message object instead of '
2383 . 'a string.', E_USER_NOTICE
);
2385 $this->addHTML( $msg->parseAsBlock() );
2387 $this->addWikiMsgArray( $msg, $params );
2390 $this->returnToMain();
2394 * Output a standard permission error page
2396 * @param array $errors Error message keys
2397 * @param string $action Action that was denied or null if unknown
2399 public function showPermissionsErrorPage( array $errors, $action = null ) {
2400 // For some action (read, edit, create and upload), display a "login to do this action"
2401 // error if all of the following conditions are met:
2402 // 1. the user is not logged in
2403 // 2. the only error is insufficient permissions (i.e. no block or something else)
2404 // 3. the error can be avoided simply by logging in
2405 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2406 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2407 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2408 && ( User
::groupHasPermission( 'user', $action )
2409 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2411 $displayReturnto = null;
2413 # Due to bug 32276, if a user does not have read permissions,
2414 # $this->getTitle() will just give Special:Badtitle, which is
2415 # not especially useful as a returnto parameter. Use the title
2416 # from the request instead, if there was one.
2417 $request = $this->getRequest();
2418 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2419 if ( $action == 'edit' ) {
2420 $msg = 'whitelistedittext';
2421 $displayReturnto = $returnto;
2422 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2423 $msg = 'nocreatetext';
2424 } elseif ( $action == 'upload' ) {
2425 $msg = 'uploadnologintext';
2427 $msg = 'loginreqpagetext';
2428 $displayReturnto = Title
::newMainPage();
2434 $query['returnto'] = $returnto->getPrefixedText();
2436 if ( !$request->wasPosted() ) {
2437 $returntoquery = $request->getValues();
2438 unset( $returntoquery['title'] );
2439 unset( $returntoquery['returnto'] );
2440 unset( $returntoquery['returntoquery'] );
2441 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2444 $loginLink = Linker
::linkKnown(
2445 SpecialPage
::getTitleFor( 'Userlogin' ),
2446 $this->msg( 'loginreqlink' )->escaped(),
2451 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2452 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2454 # Don't return to a page the user can't read otherwise
2455 # we'll end up in a pointless loop
2456 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2457 $this->returnToMain( null, $displayReturnto );
2460 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2461 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2466 * Display an error page indicating that a given version of MediaWiki is
2467 * required to use it
2469 * @param mixed $version The version of MediaWiki needed to use the page
2471 public function versionRequired( $version ) {
2472 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2474 $this->addWikiMsg( 'versionrequiredtext', $version );
2475 $this->returnToMain();
2479 * Format a list of error messages
2481 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2482 * @param string $action Action that was denied or null if unknown
2483 * @return string The wikitext error-messages, formatted into a list.
2485 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2486 if ( $action == null ) {
2487 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2489 $action_desc = $this->msg( "action-$action" )->plain();
2491 'permissionserrorstext-withaction',
2494 )->plain() . "\n\n";
2497 if ( count( $errors ) > 1 ) {
2498 $text .= '<ul class="permissions-errors">' . "\n";
2500 foreach ( $errors as $error ) {
2502 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2507 $text .= "<div class=\"permissions-errors\">\n" .
2508 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2516 * Display a page stating that the Wiki is in read-only mode.
2517 * Should only be called after wfReadOnly() has returned true.
2519 * Historically, this function was used to show the source of the page that the user
2520 * was trying to edit and _also_ permissions error messages. The relevant code was
2521 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2523 * @deprecated since 1.25; throw the exception directly
2524 * @throws ReadOnlyError
2526 public function readOnlyPage() {
2527 if ( func_num_args() > 0 ) {
2528 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2531 throw new ReadOnlyError
;
2535 * Turn off regular page output and return an error response
2536 * for when rate limiting has triggered.
2538 * @deprecated since 1.25; throw the exception directly
2540 public function rateLimited() {
2541 wfDeprecated( __METHOD__
, '1.25' );
2542 throw new ThrottledError
;
2546 * Show a warning about slave lag
2548 * If the lag is higher than $wgSlaveLagCritical seconds,
2549 * then the warning is a bit more obvious. If the lag is
2550 * lower than $wgSlaveLagWarning, then no warning is shown.
2552 * @param int $lag Slave lag
2554 public function showLagWarning( $lag ) {
2555 $config = $this->getConfig();
2556 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2557 $message = $lag < $config->get( 'SlaveLagCritical' )
2560 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2561 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2565 public function showFatalError( $message ) {
2566 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2568 $this->addHTML( $message );
2571 public function showUnexpectedValueError( $name, $val ) {
2572 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2575 public function showFileCopyError( $old, $new ) {
2576 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2579 public function showFileRenameError( $old, $new ) {
2580 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2583 public function showFileDeleteError( $name ) {
2584 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2587 public function showFileNotFoundError( $name ) {
2588 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2592 * Add a "return to" link pointing to a specified title
2594 * @param Title $title Title to link
2595 * @param array $query Query string parameters
2596 * @param string $text Text of the link (input is not escaped)
2597 * @param array $options Options array to pass to Linker
2599 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2600 $link = $this->msg( 'returnto' )->rawParams(
2601 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2602 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2606 * Add a "return to" link pointing to a specified title,
2607 * or the title indicated in the request, or else the main page
2609 * @param mixed $unused
2610 * @param Title|string $returnto Title or String to return to
2611 * @param string $returntoquery Query string for the return to link
2613 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2614 if ( $returnto == null ) {
2615 $returnto = $this->getRequest()->getText( 'returnto' );
2618 if ( $returntoquery == null ) {
2619 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2622 if ( $returnto === '' ) {
2623 $returnto = Title
::newMainPage();
2626 if ( is_object( $returnto ) ) {
2627 $titleObj = $returnto;
2629 $titleObj = Title
::newFromText( $returnto );
2631 if ( !is_object( $titleObj ) ) {
2632 $titleObj = Title
::newMainPage();
2635 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2639 * @param Skin $sk The given Skin
2640 * @param bool $includeStyle Unused
2641 * @return string The doctype, opening "<html>", and head element.
2643 public function headElement( Skin
$sk, $includeStyle = true ) {
2646 $userdir = $this->getLanguage()->getDir();
2647 $sitedir = $wgContLang->getDir();
2649 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2651 if ( $this->getHTMLTitle() == '' ) {
2652 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2655 $openHead = Html
::openElement( 'head' );
2657 # Don't bother with the newline if $head == ''
2658 $ret .= "$openHead\n";
2661 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2662 // Add <meta charset="UTF-8">
2663 // This should be before <title> since it defines the charset used by
2664 // text including the text inside <title>.
2665 // The spec recommends defining XHTML5's charset using the XML declaration
2667 // Our XML declaration is output by Html::htmlHeader.
2668 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2669 // http://www.whatwg.org/html/semantics.html#charset
2670 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2673 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2674 $ret .= $this->getInlineHeadScripts() . "\n";
2675 $ret .= $this->buildCssLinks() . "\n";
2676 $ret .= $this->getExternalHeadScripts() . "\n";
2678 foreach ( $this->getHeadLinksArray() as $item ) {
2679 $ret .= $item . "\n";
2682 foreach ( $this->mHeadItems
as $item ) {
2683 $ret .= $item . "\n";
2686 $closeHead = Html
::closeElement( 'head' );
2688 $ret .= "$closeHead\n";
2691 $bodyClasses = array();
2692 $bodyClasses[] = 'mediawiki';
2694 # Classes for LTR/RTL directionality support
2695 $bodyClasses[] = $userdir;
2696 $bodyClasses[] = "sitedir-$sitedir";
2698 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2699 # A <body> class is probably not the best way to do this . . .
2700 $bodyClasses[] = 'capitalize-all-nouns';
2703 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2704 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2706 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2708 $bodyAttrs = array();
2709 // While the implode() is not strictly needed, it's used for backwards compatibility
2710 // (this used to be built as a string and hooks likely still expect that).
2711 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2713 // Allow skins and extensions to add body attributes they need
2714 $sk->addToBodyAttributes( $this, $bodyAttrs );
2715 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2717 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2723 * Get a ResourceLoader object associated with this OutputPage
2725 * @return ResourceLoader
2727 public function getResourceLoader() {
2728 if ( is_null( $this->mResourceLoader
) ) {
2729 $this->mResourceLoader
= new ResourceLoader(
2731 LoggerFactory
::getInstance( 'resourceloader' )
2734 return $this->mResourceLoader
;
2738 * Construct neccecary html and loader preset states to load modules on a page.
2740 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2742 * @param array|string $modules One or more module names
2743 * @param string $only ResourceLoaderModule TYPE_ class constant
2744 * @param array $extraQuery [optional] Array with extra query parameters for the request
2745 * @return array A list of HTML strings and array of client loader preset states
2747 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = array() ) {
2748 $modules = (array)$modules;
2751 // List of html strings
2753 // Associative array of module names and their states
2754 'states' => array(),
2757 if ( !count( $modules ) ) {
2761 if ( count( $modules ) > 1 ) {
2762 // Remove duplicate module requests
2763 $modules = array_unique( $modules );
2764 // Sort module names so requests are more uniform
2767 if ( ResourceLoader
::inDebugMode() ) {
2768 // Recursively call us for every item
2769 foreach ( $modules as $name ) {
2770 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2771 $links['html'] = array_merge( $links['html'], $link['html'] );
2772 $links['states'] +
= $link['states'];
2778 if ( !is_null( $this->mTarget
) ) {
2779 $extraQuery['target'] = $this->mTarget
;
2782 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2783 $sortedModules = array();
2784 $resourceLoader = $this->getResourceLoader();
2785 foreach ( $modules as $name ) {
2786 $module = $resourceLoader->getModule( $name );
2787 # Check that we're allowed to include this module on this page
2789 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2790 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2791 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2792 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2793 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2794 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2795 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2800 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2803 foreach ( $sortedModules as $source => $groups ) {
2804 foreach ( $groups as $group => $grpModules ) {
2805 // Special handling for user-specific groups
2807 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2808 $user = $this->getUser()->getName();
2811 // Create a fake request based on the one we are about to make so modules return
2812 // correct timestamp and emptiness data
2813 $query = ResourceLoader
::makeLoaderQuery(
2814 array(), // modules; not determined yet
2815 $this->getLanguage()->getCode(),
2816 $this->getSkin()->getSkinName(),
2818 null, // version; not determined yet
2819 ResourceLoader
::inDebugMode(),
2820 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2821 $this->isPrintable(),
2822 $this->getRequest()->getBool( 'handheld' ),
2825 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2827 // Extract modules that know they're empty and see if we have one or more
2830 foreach ( $grpModules as $key => $module ) {
2831 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2832 // If we're only getting the styles, we don't need to do anything for empty modules.
2833 if ( $module->isKnownEmpty( $context ) ) {
2834 unset( $grpModules[$key] );
2835 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2836 $links['states'][$key] = 'ready';
2840 $isRaw |
= $module->isRaw();
2843 // If there are no non-empty modules, skip this group
2844 if ( count( $grpModules ) === 0 ) {
2848 // Inline private modules. These can't be loaded through load.php for security
2849 // reasons, see bug 34907. Note that these modules should be loaded from
2850 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2851 // properly use them as dependencies (bug 30914)
2852 if ( $group === 'private' ) {
2853 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2854 $links['html'][] = Html
::inlineStyle(
2855 $resourceLoader->makeModuleResponse( $context, $grpModules )
2858 $links['html'][] = ResourceLoader
::makeInlineScript(
2859 $resourceLoader->makeModuleResponse( $context, $grpModules )
2865 // Special handling for the user group; because users might change their stuff
2866 // on-wiki like user pages, or user preferences; we need to find the highest
2867 // timestamp of these user-changeable modules so we can ensure cache misses on change
2868 // This should NOT be done for the site group (bug 27564) because anons get that too
2869 // and we shouldn't be putting timestamps in CDN-cached HTML
2871 if ( $group === 'user' ) {
2872 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2875 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2876 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2877 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2879 // Automatically select style/script elements
2880 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2881 $link = Html
::linkedStyle( $url );
2883 if ( $context->getRaw() ||
$isRaw ) {
2884 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2885 $link = Html
::element( 'script', array(
2886 // In SpecialJavaScriptTest, QUnit must load synchronous
2887 'async' => !isset( $extraQuery['sync'] ),
2891 $link = ResourceLoader
::makeInlineScript(
2892 Xml
::encodeJsCall( 'mw.loader.load', array( $url ) )
2896 // For modules requested directly in the html via <script> or mw.loader.load
2897 // tell mw.loader they are being loading to prevent duplicate requests.
2898 foreach ( $grpModules as $key => $module ) {
2899 // Don't output state=loading for the startup module.
2900 if ( $key !== 'startup' ) {
2901 $links['states'][$key] = 'loading';
2906 if ( $group == 'noscript' ) {
2907 $links['html'][] = Html
::rawElement( 'noscript', array(), $link );
2909 $links['html'][] = $link;
2918 * Build html output from an array of links from makeResourceLoaderLink.
2919 * @param array $links
2920 * @return string HTML
2922 protected static function getHtmlFromLoaderLinks( array $links ) {
2925 foreach ( $links as $link ) {
2926 if ( !is_array( $link ) ) {
2929 $html = array_merge( $html, $link['html'] );
2930 $states +
= $link['states'];
2933 // Filter out empty values
2934 $html = array_filter( $html, 'strlen' );
2936 if ( count( $states ) ) {
2937 array_unshift( $html, ResourceLoader
::makeInlineScript(
2938 ResourceLoader
::makeLoaderStateScript( $states )
2942 return WrappedString
::join( "\n", $html );
2946 * JS stuff to put in the "<head>". This is the startup module, config
2947 * vars and modules marked with position 'top'
2949 * @return string HTML fragment
2951 function getHeadScripts() {
2952 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2956 * <script src="..."> tags for "<head>". This is the startup module
2957 * and other modules marked with position 'top'.
2959 * @return string HTML fragment
2961 function getExternalHeadScripts() {
2964 // Startup - this provides the client with the module
2965 // manifest and loads jquery and mediawiki base modules
2966 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
2968 return self
::getHtmlFromLoaderLinks( $links );
2972 * <script>...</script> tags to put in "<head>".
2974 * @return string HTML fragment
2976 function getInlineHeadScripts() {
2979 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
2980 // Must be done synchronously on every page to avoid flashes of wrong content.
2981 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
2982 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
2983 // For the performance benefit of the majority, this is added unconditionally here and is
2984 // then fixed up by the startup module for unsupported browsers.
2985 $links[] = Html
::inlineScript(
2986 'document.documentElement.className = document.documentElement.className'
2987 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
2990 // Load config before anything else
2991 $links[] = ResourceLoader
::makeInlineScript(
2992 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2995 // Load embeddable private modules before any loader links
2996 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2997 // in mw.loader.implement() calls and deferred until mw.user is available
2998 $embedScripts = array( 'user.options' );
2999 $links[] = $this->makeResourceLoaderLink(
3001 ResourceLoaderModule
::TYPE_COMBINED
3003 // Separate user.tokens as otherwise caching will be allowed (T84960)
3004 $links[] = $this->makeResourceLoaderLink(
3006 ResourceLoaderModule
::TYPE_COMBINED
3009 // Modules requests - let the client calculate dependencies and batch requests as it likes
3010 // Only load modules that have marked themselves for loading at the top
3011 $modules = $this->getModules( true, 'top' );
3013 $links[] = ResourceLoader
::makeInlineScript(
3014 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3018 // "Scripts only" modules marked for top inclusion
3019 $links[] = $this->makeResourceLoaderLink(
3020 $this->getModuleScripts( true, 'top' ),
3021 ResourceLoaderModule
::TYPE_SCRIPTS
3024 return self
::getHtmlFromLoaderLinks( $links );
3028 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3029 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3030 * site JS, and user JS.
3032 * @param bool $unused Previously used to let this method change its output based
3033 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3036 function getScriptsForBottomQueue( $unused = null ) {
3037 // Scripts "only" requests marked for bottom inclusion
3038 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3041 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3042 ResourceLoaderModule
::TYPE_SCRIPTS
3045 // Modules requests - let the client calculate dependencies and batch requests as it likes
3046 // Only load modules that have marked themselves for loading at the bottom
3047 $modules = $this->getModules( true, 'bottom' );
3049 $links[] = ResourceLoader
::makeInlineScript(
3050 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3055 $links[] = $this->mScripts
;
3057 // Add user JS if enabled
3058 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3059 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3060 if ( $this->getConfig()->get( 'AllowUserJs' )
3061 && $this->getUser()->isLoggedIn()
3062 && $this->getTitle()
3063 && $this->getTitle()->isJsSubpage()
3064 && $this->userCanPreview()
3066 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3067 // and include the draft contents as a raw script instead.
3068 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3069 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3071 // Load the previewed JS
3072 $links[] = ResourceLoader
::makeInlineScript(
3073 Xml
::encodeJsCall( 'mw.loader.using', array(
3074 array( 'user', 'site' ),
3077 . Xml
::encodeJsCall( '$.globalEval', array(
3078 $this->getRequest()->getText( 'wpTextbox1' )
3085 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3086 // asynchronously and may arrive *after* the inline script here. So the previewed code
3087 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3088 // Similarly, when previewing ./common.js and the user module does arrive first,
3089 // it will arrive without common.js and the inline script runs after.
3090 // Thus running common after the excluded subpage.
3092 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3093 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3096 // Group JS is only enabled if site JS is enabled.
3097 $links[] = $this->makeResourceLoaderLink(
3099 ResourceLoaderModule
::TYPE_COMBINED
3102 return self
::getHtmlFromLoaderLinks( $links );
3106 * JS stuff to put at the bottom of the "<body>"
3109 function getBottomScripts() {
3110 return $this->getScriptsForBottomQueue();
3114 * Get the javascript config vars to include on this page
3116 * @return array Array of javascript config vars
3119 public function getJsConfigVars() {
3120 return $this->mJsConfigVars
;
3124 * Add one or more variables to be set in mw.config in JavaScript
3126 * @param string|array $keys Key or array of key/value pairs
3127 * @param mixed $value [optional] Value of the configuration variable
3129 public function addJsConfigVars( $keys, $value = null ) {
3130 if ( is_array( $keys ) ) {
3131 foreach ( $keys as $key => $value ) {
3132 $this->mJsConfigVars
[$key] = $value;
3137 $this->mJsConfigVars
[$keys] = $value;
3141 * Get an array containing the variables to be set in mw.config in JavaScript.
3143 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3144 * - in other words, page-independent/site-wide variables (without state).
3145 * You will only be adding bloat to the html page and causing page caches to
3146 * have to be purged on configuration changes.
3149 public function getJSVars() {
3154 $canonicalSpecialPageName = false; # bug 21115
3156 $title = $this->getTitle();
3157 $ns = $title->getNamespace();
3158 $canonicalNamespace = MWNamespace
::exists( $ns )
3159 ? MWNamespace
::getCanonicalName( $ns )
3160 : $title->getNsText();
3162 $sk = $this->getSkin();
3163 // Get the relevant title so that AJAX features can use the correct page name
3164 // when making API requests from certain special pages (bug 34972).
3165 $relevantTitle = $sk->getRelevantTitle();
3166 $relevantUser = $sk->getRelevantUser();
3168 if ( $ns == NS_SPECIAL
) {
3169 list( $canonicalSpecialPageName, /*...*/ ) =
3170 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3171 } elseif ( $this->canUseWikiPage() ) {
3172 $wikiPage = $this->getWikiPage();
3173 $curRevisionId = $wikiPage->getLatest();
3174 $articleId = $wikiPage->getId();
3177 $lang = $title->getPageLanguage();
3179 // Pre-process information
3180 $separatorTransTable = $lang->separatorTransformTable();
3181 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3182 $compactSeparatorTransTable = array(
3183 implode( "\t", array_keys( $separatorTransTable ) ),
3184 implode( "\t", $separatorTransTable ),
3186 $digitTransTable = $lang->digitTransformTable();
3187 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3188 $compactDigitTransTable = array(
3189 implode( "\t", array_keys( $digitTransTable ) ),
3190 implode( "\t", $digitTransTable ),
3193 $user = $this->getUser();
3196 'wgCanonicalNamespace' => $canonicalNamespace,
3197 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3198 'wgNamespaceNumber' => $title->getNamespace(),
3199 'wgPageName' => $title->getPrefixedDBkey(),
3200 'wgTitle' => $title->getText(),
3201 'wgCurRevisionId' => $curRevisionId,
3202 'wgRevisionId' => (int)$this->getRevisionId(),
3203 'wgArticleId' => $articleId,
3204 'wgIsArticle' => $this->isArticle(),
3205 'wgIsRedirect' => $title->isRedirect(),
3206 'wgAction' => Action
::getActionName( $this->getContext() ),
3207 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3208 'wgUserGroups' => $user->getEffectiveGroups(),
3209 'wgCategories' => $this->getCategories(),
3210 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3211 'wgPageContentLanguage' => $lang->getCode(),
3212 'wgPageContentModel' => $title->getContentModel(),
3213 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3214 'wgDigitTransformTable' => $compactDigitTransTable,
3215 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3216 'wgMonthNames' => $lang->getMonthNamesArray(),
3217 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3218 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3219 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3222 if ( $user->isLoggedIn() ) {
3223 $vars['wgUserId'] = $user->getId();
3224 $vars['wgUserEditCount'] = $user->getEditCount();
3225 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3226 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3227 // Get the revision ID of the oldest new message on the user's talk
3228 // page. This can be used for constructing new message alerts on
3230 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3233 if ( $wgContLang->hasVariants() ) {
3234 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3236 // Same test as SkinTemplate
3237 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3238 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3240 foreach ( $title->getRestrictionTypes() as $type ) {
3241 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3244 if ( $title->isMainPage() ) {
3245 $vars['wgIsMainPage'] = true;
3248 if ( $this->mRedirectedFrom
) {
3249 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3252 if ( $relevantUser ) {
3253 $vars['wgRelevantUserName'] = $relevantUser->getName();
3256 // Allow extensions to add their custom variables to the mw.config map.
3257 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3258 // page-dependant but site-wide (without state).
3259 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3260 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3262 // Merge in variables from addJsConfigVars last
3263 return array_merge( $vars, $this->getJsConfigVars() );
3267 * To make it harder for someone to slip a user a fake
3268 * user-JavaScript or user-CSS preview, a random token
3269 * is associated with the login session. If it's not
3270 * passed back with the preview request, we won't render
3275 public function userCanPreview() {
3276 $request = $this->getRequest();
3278 $request->getVal( 'action' ) !== 'submit' ||
3279 !$request->getCheck( 'wpPreview' ) ||
3280 !$request->wasPosted()
3285 $user = $this->getUser();
3286 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3290 $title = $this->getTitle();
3291 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3294 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3295 // Don't execute another user's CSS or JS on preview (T85855)
3299 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3300 if ( count( $errors ) !== 0 ) {
3308 * @return array Array in format "link name or number => 'link html'".
3310 public function getHeadLinksArray() {
3314 $config = $this->getConfig();
3316 $canonicalUrl = $this->mCanonicalUrl
;
3318 $tags['meta-generator'] = Html
::element( 'meta', array(
3319 'name' => 'generator',
3320 'content' => "MediaWiki $wgVersion",
3323 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3324 $tags['meta-referrer'] = Html
::element( 'meta', array(
3325 'name' => 'referrer',
3326 'content' => $config->get( 'ReferrerPolicy' )
3330 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3331 if ( $p !== 'index,follow' ) {
3332 // http://www.robotstxt.org/wc/meta-user.html
3333 // Only show if it's different from the default robots policy
3334 $tags['meta-robots'] = Html
::element( 'meta', array(
3340 foreach ( $this->mMetatags
as $tag ) {
3341 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3343 $tag[0] = substr( $tag[0], 5 );
3347 $tagName = "meta-{$tag[0]}";
3348 if ( isset( $tags[$tagName] ) ) {
3349 $tagName .= $tag[1];
3351 $tags[$tagName] = Html
::element( 'meta',
3354 'content' => $tag[1]
3359 foreach ( $this->mLinktags
as $tag ) {
3360 $tags[] = Html
::element( 'link', $tag );
3363 # Universal edit button
3364 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3365 $user = $this->getUser();
3366 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3367 && ( $this->getTitle()->exists() ||
3368 $this->getTitle()->quickUserCan( 'create', $user ) )
3370 // Original UniversalEditButton
3371 $msg = $this->msg( 'edit' )->text();
3372 $tags['universal-edit-button'] = Html
::element( 'link', array(
3373 'rel' => 'alternate',
3374 'type' => 'application/x-wiki',
3376 'href' => $this->getTitle()->getEditURL(),
3378 // Alternate edit link
3379 $tags['alternative-edit'] = Html
::element( 'link', array(
3382 'href' => $this->getTitle()->getEditURL(),
3387 # Generally the order of the favicon and apple-touch-icon links
3388 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3389 # uses whichever one appears later in the HTML source. Make sure
3390 # apple-touch-icon is specified first to avoid this.
3391 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3392 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3393 'rel' => 'apple-touch-icon',
3394 'href' => $config->get( 'AppleTouchIcon' )
3398 if ( $config->get( 'Favicon' ) !== false ) {
3399 $tags['favicon'] = Html
::element( 'link', array(
3400 'rel' => 'shortcut icon',
3401 'href' => $config->get( 'Favicon' )
3405 # OpenSearch description link
3406 $tags['opensearch'] = Html
::element( 'link', array(
3408 'type' => 'application/opensearchdescription+xml',
3409 'href' => wfScript( 'opensearch_desc' ),
3410 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3413 if ( $config->get( 'EnableAPI' ) ) {
3414 # Real Simple Discovery link, provides auto-discovery information
3415 # for the MediaWiki API (and potentially additional custom API
3416 # support such as WordPress or Twitter-compatible APIs for a
3417 # blogging extension, etc)
3418 $tags['rsd'] = Html
::element( 'link', array(
3420 'type' => 'application/rsd+xml',
3421 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3422 // Whether RSD accepts relative or protocol-relative URLs is completely
3423 // undocumented, though.
3424 'href' => wfExpandUrl( wfAppendQuery(
3426 array( 'action' => 'rsd' ) ),
3433 if ( !$config->get( 'DisableLangConversion' ) ) {
3434 $lang = $this->getTitle()->getPageLanguage();
3435 if ( $lang->hasVariants() ) {
3436 $variants = $lang->getVariants();
3437 foreach ( $variants as $variant ) {
3438 $tags["variant-$variant"] = Html
::element( 'link', array(
3439 'rel' => 'alternate',
3440 'hreflang' => wfBCP47( $variant ),
3441 'href' => $this->getTitle()->getLocalURL(
3442 array( 'variant' => $variant ) )
3446 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3447 $tags["variant-x-default"] = Html
::element( 'link', array(
3448 'rel' => 'alternate',
3449 'hreflang' => 'x-default',
3450 'href' => $this->getTitle()->getLocalURL() ) );
3455 if ( $this->copyrightUrl
!== null ) {
3456 $copyright = $this->copyrightUrl
;
3459 if ( $config->get( 'RightsPage' ) ) {
3460 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3463 $copyright = $copy->getLocalURL();
3467 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3468 $copyright = $config->get( 'RightsUrl' );
3473 $tags['copyright'] = Html
::element( 'link', array(
3474 'rel' => 'copyright',
3475 'href' => $copyright )
3480 if ( $config->get( 'Feed' ) ) {
3481 $feedLinks = array();
3483 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3484 # Use the page name for the title. In principle, this could
3485 # lead to issues with having the same name for different feeds
3486 # corresponding to the same page, but we can't avoid that at
3489 $feedLinks[] = $this->feedLink(
3492 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3494 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3499 # Recent changes feed should appear on every page (except recentchanges,
3500 # that would be redundant). Put it after the per-page feed to avoid
3501 # changing existing behavior. It's still available, probably via a
3502 # menu in your browser. Some sites might have a different feed they'd
3503 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3504 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3505 # If so, use it instead.
3506 $sitename = $config->get( 'Sitename' );
3507 if ( $config->get( 'OverrideSiteFeed' ) ) {
3508 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3509 // Note, this->feedLink escapes the url.
3510 $feedLinks[] = $this->feedLink(
3513 $this->msg( "site-{$type}-feed", $sitename )->text()
3516 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3517 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3518 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3519 $feedLinks[] = $this->feedLink(
3521 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3522 # For grep: 'site-rss-feed', 'site-atom-feed'
3523 $this->msg( "site-{$format}-feed", $sitename )->text()
3528 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3529 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3530 # use OutputPage::addFeedLink() instead.
3531 Hooks
::run( 'AfterBuildFeedLinks', array( &$feedLinks ) );
3533 $tags +
= $feedLinks;
3537 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3538 if ( $canonicalUrl !== false ) {
3539 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3541 if ( $this->isArticleRelated() ) {
3542 // This affects all requests where "setArticleRelated" is true. This is
3543 // typically all requests that show content (query title, curid, oldid, diff),
3544 // and all wikipage actions (edit, delete, purge, info, history etc.).
3545 // It does not apply to File pages and Special pages.
3546 // 'history' and 'info' actions address page metadata rather than the page
3547 // content itself, so they may not be canonicalized to the view page url.
3548 // TODO: this ought to be better encapsulated in the Action class.
3549 $action = Action
::getActionName( $this->getContext() );
3550 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3551 $query = "action={$action}";
3555 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3557 $reqUrl = $this->getRequest()->getRequestURL();
3558 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3562 if ( $canonicalUrl !== false ) {
3563 $tags[] = Html
::element( 'link', array(
3564 'rel' => 'canonical',
3565 'href' => $canonicalUrl
3573 * @return string HTML tag links to be put in the header.
3574 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3575 * OutputPage::getHeadLinksArray directly.
3577 public function getHeadLinks() {
3578 wfDeprecated( __METHOD__
, '1.24' );
3579 return implode( "\n", $this->getHeadLinksArray() );
3583 * Generate a "<link rel/>" for a feed.
3585 * @param string $type Feed type
3586 * @param string $url URL to the feed
3587 * @param string $text Value of the "title" attribute
3588 * @return string HTML fragment
3590 private function feedLink( $type, $url, $text ) {
3591 return Html
::element( 'link', array(
3592 'rel' => 'alternate',
3593 'type' => "application/$type+xml",
3600 * Add a local or specified stylesheet, with the given media options.
3601 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3603 * @param string $style URL to the file
3604 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3605 * @param string $condition For IE conditional comments, specifying an IE version
3606 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3608 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3610 // Even though we expect the media type to be lowercase, but here we
3611 // force it to lowercase to be safe.
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 ) . "\n";
3640 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3641 * These will be applied to various media & IE conditionals.
3645 public function buildCssLinks() {
3648 $this->getSkin()->setupSkinUserCss( $this );
3650 // Add ResourceLoader styles
3651 // Split the styles into these groups
3656 'private' => array(),
3657 'noscript' => array()
3660 $otherTags = array(); // Tags to append after the normal <link> tags
3661 $resourceLoader = $this->getResourceLoader();
3663 $moduleStyles = $this->getModuleStyles();
3665 // Per-site custom styles
3666 $moduleStyles[] = 'site';
3667 $moduleStyles[] = 'noscript';
3668 $moduleStyles[] = 'user.groups';
3670 // Per-user custom styles
3671 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3672 && $this->userCanPreview()
3674 // We're on a preview of a CSS subpage
3675 // Exclude this page from the user module in case it's in there (bug 26283)
3676 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
,
3677 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3679 $otherTags = array_merge( $otherTags, $link['html'] );
3681 // Load the previewed CSS
3682 // If needed, Janus it first. This is user-supplied CSS, so it's
3683 // assumed to be right for the content language directionality.
3684 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3685 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3686 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3688 $otherTags[] = Html
::inlineStyle( $previewedCSS ) . "\n";
3690 // Load the user styles normally
3691 $moduleStyles[] = 'user';
3694 // Per-user preference styles
3695 $moduleStyles[] = 'user.cssprefs';
3697 foreach ( $moduleStyles as $name ) {
3698 $module = $resourceLoader->getModule( $name );
3702 if ( $name === 'site' ) {
3703 // HACK: The site module shouldn't be fragmented with a cache group and
3704 // http request. But in order to ensure its styles are separated and after the
3705 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3706 // The scripts remain ungrouped and rides the bottom queue.
3707 $styles['site'][] = $name;
3710 $group = $module->getGroup();
3711 // Modules in groups other than the ones needing special treatment
3712 // (see $styles assignment)
3713 // will be placed in the "other" style category.
3714 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3717 // We want site, private and user styles to override dynamically added
3718 // styles from modules, but we want dynamically added styles to override
3719 // statically added styles from other modules. So the order has to be
3720 // other, dynamic, site, private, user. Add statically added styles for
3722 $links[] = $this->makeResourceLoaderLink(
3724 ResourceLoaderModule
::TYPE_STYLES
3726 // Add normal styles added through addStyle()/addInlineStyle() here
3727 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3728 // Add marker tag to mark the place where the client-side
3729 // loader should inject dynamic styles
3730 // We use a <meta> tag with a made-up name for this because that's valid HTML
3731 $links[] = Html
::element(
3733 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3736 // Add site-specific and user-specific styles
3737 // 'private' at present only contains user.options, so put that before 'user'
3738 // Any future private modules will likely have a similar user-specific character
3739 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3740 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3741 ResourceLoaderModule
::TYPE_STYLES
3745 // Add stuff in $otherTags (previewed user CSS if applicable)
3746 return self
::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3752 public function buildCssLinksArray() {
3755 // Add any extension CSS
3756 foreach ( $this->mExtStyles
as $url ) {
3757 $this->addStyle( $url );
3759 $this->mExtStyles
= array();
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 "media" attribute based on request parameters
3815 * @param string $media Current value of the "media" attribute
3816 * @return string Modified value of the "media" attribute, or null to skip
3819 public static function transformCssMedia( $media ) {
3822 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3823 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3825 // Switch in on-screen display for media testing
3827 'printable' => 'print',
3828 'handheld' => 'handheld',
3830 foreach ( $switches as $switch => $targetMedia ) {
3831 if ( $wgRequest->getBool( $switch ) ) {
3832 if ( $media == $targetMedia ) {
3834 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3835 /* This regex will not attempt to understand a comma-separated media_query_list
3837 * Example supported values for $media:
3838 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3839 * Example NOT supported value for $media:
3840 * '3d-glasses, screen, print and resolution > 90dpi'
3842 * If it's a print request, we never want any kind of screen stylesheets
3843 * If it's a handheld request (currently the only other choice with a switch),
3844 * we don't want simple 'screen' but we might want screen queries that
3845 * have a max-width or something, so we'll pass all others on and let the
3846 * client do the query.
3848 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3859 * Add a wikitext-formatted message to the output.
3860 * This is equivalent to:
3862 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3864 public function addWikiMsg( /*...*/ ) {
3865 $args = func_get_args();
3866 $name = array_shift( $args );
3867 $this->addWikiMsgArray( $name, $args );
3871 * Add a wikitext-formatted message to the output.
3872 * Like addWikiMsg() except the parameters are taken as an array
3873 * instead of a variable argument list.
3875 * @param string $name
3876 * @param array $args
3878 public function addWikiMsgArray( $name, $args ) {
3879 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3883 * This function takes a number of message/argument specifications, wraps them in
3884 * some overall structure, and then parses the result and adds it to the output.
3886 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3887 * and so on. The subsequent arguments may be either
3888 * 1) strings, in which case they are message names, or
3889 * 2) arrays, in which case, within each array, the first element is the message
3890 * name, and subsequent elements are the parameters to that message.
3892 * Don't use this for messages that are not in the user's interface language.
3896 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3900 * $wgOut->addWikiText( "<div class='error'>\n"
3901 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3903 * The newline after the opening div is needed in some wikitext. See bug 19226.
3905 * @param string $wrap
3907 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3908 $msgSpecs = func_get_args();
3909 array_shift( $msgSpecs );
3910 $msgSpecs = array_values( $msgSpecs );
3912 foreach ( $msgSpecs as $n => $spec ) {
3913 if ( is_array( $spec ) ) {
3915 $name = array_shift( $args );
3916 if ( isset( $args['options'] ) ) {
3917 unset( $args['options'] );
3919 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3927 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3929 $this->addWikiText( $s );
3933 * Enables/disables TOC, doesn't override __NOTOC__
3937 public function enableTOC( $flag = true ) {
3938 $this->mEnableTOC
= $flag;
3945 public function isTOCEnabled() {
3946 return $this->mEnableTOC
;
3950 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3954 public function enableSectionEditLinks( $flag = true ) {
3955 $this->mEnableSectionEditLinks
= $flag;
3962 public function sectionEditLinksEnabled() {
3963 return $this->mEnableSectionEditLinks
;
3967 * Helper function to setup the PHP implementation of OOUI to use in this request.
3970 * @param String $skinName The Skin name to determine the correct OOUI theme
3971 * @param String $dir Language direction
3973 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3974 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3975 // Make keys (skin names) lowercase for case-insensitive matching.
3976 $themes = array_change_key_case( $themes, CASE_LOWER
);
3977 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3978 // For example, 'OOUI\MediaWikiTheme'.
3979 $themeClass = "OOUI\\{$theme}Theme";
3980 OOUI\Theme
::setSingleton( new $themeClass() );
3981 OOUI\Element
::setDefaultDir( $dir );
3985 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3986 * MediaWiki and this OutputPage instance.
3990 public function enableOOUI() {
3992 strtolower( $this->getSkin()->getSkinName() ),
3993 $this->getLanguage()->getDir()
3995 $this->addModuleStyles( array(
3997 'oojs-ui.styles.icons',
3998 'oojs-ui.styles.indicators',
3999 'oojs-ui.styles.textures',
4000 'mediawiki.widgets.styles',