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 = '';
233 private $mParseWarnings = array();
235 /** @var int Cache stuff. Looks like mEnableClientCache */
236 protected $mSquidMaxage = 0;
237 /** @var int Upper limit on mSquidMaxage */
238 protected $mCdnMaxageLimit = INF
;
241 * @var bool Controls if anti-clickjacking / frame-breaking headers will
242 * be sent. This should be done for pages where edit actions are possible.
243 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
245 protected $mPreventClickjacking = true;
247 /** @var int To include the variable {{REVISIONID}} */
248 private $mRevisionId = null;
251 private $mRevisionTimestamp = null;
254 protected $mFileVersion = null;
257 * @var array An array of stylesheet filenames (relative from skins path),
258 * with options for CSS media, IE conditions, and RTL/LTR direction.
259 * For internal use; add settings in the skin via $this->addStyle()
261 * Style again! This seems like a code duplication since we already have
262 * mStyles. This is what makes Open Source amazing.
264 protected $styles = array();
267 * Whether jQuery is already handled.
269 protected $mJQueryDone = false;
271 private $mIndexPolicy = 'index';
272 private $mFollowPolicy = 'follow';
273 private $mVaryHeader = array(
274 'Accept-Encoding' => array( 'match=gzip' ),
278 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
283 private $mRedirectedFrom = null;
286 * Additional key => value data
288 private $mProperties = array();
291 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
293 private $mTarget = null;
296 * @var bool Whether parser output should contain table of contents
298 private $mEnableTOC = true;
301 * @var bool Whether parser output should contain section edit links
303 private $mEnableSectionEditLinks = true;
306 * @var string|null The URL to send in a <link> element with rel=copyright
308 private $copyrightUrl;
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
314 * @param IContextSource|null $context
316 function __construct( IContextSource
$context = null ) {
317 if ( $context === null ) {
318 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
319 wfDeprecated( __METHOD__
, '1.18' );
321 $this->setContext( $context );
326 * Redirect to $url rather than displaying the normal page
328 * @param string $url URL
329 * @param string $responsecode HTTP status code
331 public function redirect( $url, $responsecode = '302' ) {
332 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
333 $this->mRedirect
= str_replace( "\n", '', $url );
334 $this->mRedirectCode
= $responsecode;
338 * Get the URL to redirect to, or an empty string if not redirect URL set
342 public function getRedirect() {
343 return $this->mRedirect
;
347 * Set the copyright URL to send with the output.
348 * Empty string to omit, null to reset.
352 * @param string|null $url
354 public function setCopyrightUrl( $url ) {
355 $this->copyrightUrl
= $url;
359 * Set the HTTP status code to send with the output.
361 * @param int $statusCode
363 public function setStatusCode( $statusCode ) {
364 $this->mStatusCode
= $statusCode;
368 * Add a new "<meta>" tag
369 * To add an http-equiv meta tag, precede the name with "http:"
371 * @param string $name Tag name
372 * @param string $val Tag value
374 function addMeta( $name, $val ) {
375 array_push( $this->mMetatags
, array( $name, $val ) );
379 * Returns the current <meta> tags
384 public function getMetaTags() {
385 return $this->mMetatags
;
389 * Add a new \<link\> tag to the page header.
391 * Note: use setCanonicalUrl() for rel=canonical.
393 * @param array $linkarr Associative array of attributes.
395 function addLink( array $linkarr ) {
396 array_push( $this->mLinktags
, $linkarr );
400 * Returns the current <link> tags
405 public function getLinkTags() {
406 return $this->mLinktags
;
410 * Add a new \<link\> with "rel" attribute set to "meta"
412 * @param array $linkarr Associative array mapping attribute names to their
413 * values, both keys and values will be escaped, and the
414 * "rel" attribute will be automatically added
416 function addMetadataLink( array $linkarr ) {
417 $linkarr['rel'] = $this->getMetadataAttribute();
418 $this->addLink( $linkarr );
422 * Set the URL to be used for the <link rel=canonical>. This should be used
423 * in preference to addLink(), to avoid duplicate link tags.
426 function setCanonicalUrl( $url ) {
427 $this->mCanonicalUrl
= $url;
431 * Returns the URL to be used for the <link rel=canonical> if
435 * @return bool|string
437 public function getCanonicalUrl() {
438 return $this->mCanonicalUrl
;
442 * Get the value of the "rel" attribute for metadata links
446 public function getMetadataAttribute() {
447 # note: buggy CC software only reads first "meta" link
448 static $haveMeta = false;
450 return 'alternate meta';
458 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
460 * @param string $script Raw HTML
462 function addScript( $script ) {
463 $this->mScripts
.= $script . "\n";
467 * Register and add a stylesheet from an extension directory.
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 array_push( $this->mExtStyles
, $url );
479 * Get all styles added by extensions
483 function getExtStyle() {
484 return $this->mExtStyles
;
488 * Add a JavaScript file out of skins/common, or a given relative path.
490 * @param string $file Filename in skins/common or complete on-server path
492 * @param string $version Style version of the file. Defaults to $wgStyleVersion
494 public function addScriptFile( $file, $version = null ) {
495 // See if $file parameter is an absolute URL or begins with a slash
496 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
499 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
501 if ( is_null( $version ) ) {
502 $version = $this->getConfig()->get( 'StyleVersion' );
504 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
508 * Add a self-contained script tag with the given contents
510 * @param string $script JavaScript text, no "<script>" tags
512 public function addInlineScript( $script ) {
513 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
517 * Get all registered JS and CSS tags for the header.
520 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
522 function getScript() {
523 wfDeprecated( __METHOD__
, '1.24' );
524 return $this->mScripts
. $this->getHeadItems();
528 * Filter an array of modules to remove insufficiently trustworthy members, and modules
529 * which are no longer registered (eg a page is cached before an extension is disabled)
530 * @param array $modules
531 * @param string|null $position If not null, only return modules with this position
532 * @param string $type
535 protected function filterModules( array $modules, $position = null,
536 $type = ResourceLoaderModule
::TYPE_COMBINED
538 $resourceLoader = $this->getResourceLoader();
539 $filteredModules = array();
540 foreach ( $modules as $val ) {
541 $module = $resourceLoader->getModule( $val );
542 if ( $module instanceof ResourceLoaderModule
543 && $module->getOrigin() <= $this->getAllowedModules( $type )
544 && ( is_null( $position ) ||
$module->getPosition() == $position )
545 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
547 $filteredModules[] = $val;
550 return $filteredModules;
554 * Get the list of modules to include on this page
556 * @param bool $filter Whether to filter out insufficiently trustworthy modules
557 * @param string|null $position If not null, only return modules with this position
558 * @param string $param
559 * @return array Array of module names
561 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
562 $modules = array_values( array_unique( $this->$param ) );
564 ?
$this->filterModules( $modules, $position )
569 * Add one or more modules recognized by ResourceLoader. Modules added
570 * through this function will be loaded by ResourceLoader when the
573 * @param string|array $modules Module name (string) or array of module names
575 public function addModules( $modules ) {
576 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
580 * Get the list of module JS to include on this page
582 * @param bool $filter
583 * @param string|null $position
585 * @return array Array of module names
587 public function getModuleScripts( $filter = false, $position = null ) {
588 return $this->getModules( $filter, $position, 'mModuleScripts' );
592 * Add only JS of one or more modules recognized by ResourceLoader. Module
593 * scripts added through this function will be loaded by ResourceLoader when
596 * @param string|array $modules Module name (string) or array of module names
598 public function addModuleScripts( $modules ) {
599 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
603 * Get the list of module CSS to include on this page
605 * @param bool $filter
606 * @param string|null $position
608 * @return array Array of module names
610 public function getModuleStyles( $filter = false, $position = null ) {
611 return $this->getModules( $filter, $position, 'mModuleStyles' );
615 * Add only CSS of one or more modules recognized by ResourceLoader.
617 * Module styles added through this function will be added using standard link CSS
618 * tags, rather than as a combined Javascript and CSS package. Thus, they will
619 * load when JavaScript is disabled (unless CSS also happens to be disabled).
621 * @param string|array $modules Module name (string) or array of module names
623 public function addModuleStyles( $modules ) {
624 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
628 * Get the list of module messages to include on this page
630 * @deprecated since 1.26 Obsolete
631 * @param bool $filter
632 * @param string|null $position
633 * @return array Array of module names
635 public function getModuleMessages( $filter = false, $position = null ) {
636 wfDeprecated( __METHOD__
, '1.26' );
641 * Load messages of one or more ResourceLoader modules.
643 * @deprecated since 1.26 Use addModules() instead
644 * @param string|array $modules Module name (string) or array of module names
646 public function addModuleMessages( $modules ) {
647 wfDeprecated( __METHOD__
, '1.26' );
651 * @return null|string ResourceLoader target
653 public function getTarget() {
654 return $this->mTarget
;
658 * Sets ResourceLoader target for load.php links. If null, will be omitted
660 * @param string|null $target
662 public function setTarget( $target ) {
663 $this->mTarget
= $target;
667 * Get an array of head items
671 function getHeadItemsArray() {
672 return $this->mHeadItems
;
676 * Get all header items in a string
679 * @deprecated since 1.24 Use OutputPage::headElement or
680 * if absolutely necessary use OutputPage::getHeadItemsArray
682 function getHeadItems() {
683 wfDeprecated( __METHOD__
, '1.24' );
685 foreach ( $this->mHeadItems
as $item ) {
692 * Add or replace an header item to the output
694 * @param string $name Item name
695 * @param string $value Raw HTML
697 public function addHeadItem( $name, $value ) {
698 $this->mHeadItems
[$name] = $value;
702 * Check if the header item $name is already set
704 * @param string $name Item name
707 public function hasHeadItem( $name ) {
708 return isset( $this->mHeadItems
[$name] );
712 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
714 * @param string $tag Value of "ETag" header
716 function setETag( $tag ) {
721 * Set whether the output should only contain the body of the article,
722 * without any skin, sidebar, etc.
723 * Used e.g. when calling with "action=render".
725 * @param bool $only Whether to output only the body of the article
727 public function setArticleBodyOnly( $only ) {
728 $this->mArticleBodyOnly
= $only;
732 * Return whether the output will contain only the body of the article
736 public function getArticleBodyOnly() {
737 return $this->mArticleBodyOnly
;
741 * Set an additional output property
744 * @param string $name
745 * @param mixed $value
747 public function setProperty( $name, $value ) {
748 $this->mProperties
[$name] = $value;
752 * Get an additional output property
755 * @param string $name
756 * @return mixed Property value or null if not found
758 public function getProperty( $name ) {
759 if ( isset( $this->mProperties
[$name] ) ) {
760 return $this->mProperties
[$name];
767 * checkLastModified tells the client to use the client-cached page if
768 * possible. If successful, the OutputPage is disabled so that
769 * any future call to OutputPage->output() have no effect.
771 * Side effect: sets mLastModified for Last-Modified header
773 * @param string $timestamp
775 * @return bool True if cache-ok headers was sent.
777 public function checkLastModified( $timestamp ) {
778 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
779 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
782 $config = $this->getConfig();
783 if ( !$config->get( 'CachePages' ) ) {
784 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
788 $timestamp = wfTimestamp( TS_MW
, $timestamp );
789 $modifiedTimes = array(
790 'page' => $timestamp,
791 'user' => $this->getUser()->getTouched(),
792 'epoch' => $config->get( 'CacheEpoch' )
794 if ( $config->get( 'UseSquid' ) ) {
795 // bug 44570: the core page itself may not change, but resources might
796 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
798 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
800 $maxModified = max( $modifiedTimes );
801 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
803 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
804 if ( $clientHeader === false ) {
805 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
809 # IE sends sizes after the date like this:
810 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
811 # this breaks strtotime().
812 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
814 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
815 $clientHeaderTime = strtotime( $clientHeader );
816 MediaWiki\restoreWarnings
();
817 if ( !$clientHeaderTime ) {
819 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
822 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
826 foreach ( $modifiedTimes as $name => $value ) {
827 if ( $info !== '' ) {
830 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
833 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
834 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
835 wfDebug( __METHOD__
. ": effective Last-Modified: " .
836 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
837 if ( $clientHeaderTime < $maxModified ) {
838 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
843 # Give a 304 Not Modified response code and disable body output
844 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
845 ini_set( 'zlib.output_compression', 0 );
846 $this->getRequest()->response()->statusHeader( 304 );
847 $this->sendCacheControl();
850 // Don't output a compressed blob when using ob_gzhandler;
851 // it's technically against HTTP spec and seems to confuse
852 // Firefox when the response gets split over two packets.
853 wfClearOutputBuffers();
859 * Override the last modified timestamp
861 * @param string $timestamp New timestamp, in a format readable by
864 public function setLastModified( $timestamp ) {
865 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
869 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
871 * @param string $policy The literal string to output as the contents of
872 * the meta tag. Will be parsed according to the spec and output in
876 public function setRobotPolicy( $policy ) {
877 $policy = Article
::formatRobotPolicy( $policy );
879 if ( isset( $policy['index'] ) ) {
880 $this->setIndexPolicy( $policy['index'] );
882 if ( isset( $policy['follow'] ) ) {
883 $this->setFollowPolicy( $policy['follow'] );
888 * Set the index policy for the page, but leave the follow policy un-
891 * @param string $policy Either 'index' or 'noindex'.
894 public function setIndexPolicy( $policy ) {
895 $policy = trim( $policy );
896 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
897 $this->mIndexPolicy
= $policy;
902 * Set the follow policy for the page, but leave the index policy un-
905 * @param string $policy Either 'follow' or 'nofollow'.
908 public function setFollowPolicy( $policy ) {
909 $policy = trim( $policy );
910 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
911 $this->mFollowPolicy
= $policy;
916 * Set the new value of the "action text", this will be added to the
917 * "HTML title", separated from it with " - ".
919 * @param string $text New value of the "action text"
921 public function setPageTitleActionText( $text ) {
922 $this->mPageTitleActionText
= $text;
926 * Get the value of the "action text"
930 public function getPageTitleActionText() {
931 return $this->mPageTitleActionText
;
935 * "HTML title" means the contents of "<title>".
936 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
938 * @param string|Message $name
940 public function setHTMLTitle( $name ) {
941 if ( $name instanceof Message
) {
942 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
944 $this->mHTMLtitle
= $name;
949 * Return the "HTML title", i.e. the content of the "<title>" tag.
953 public function getHTMLTitle() {
954 return $this->mHTMLtitle
;
958 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
962 public function setRedirectedFrom( $t ) {
963 $this->mRedirectedFrom
= $t;
967 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
968 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
969 * but not bad tags like \<script\>. This function automatically sets
970 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
971 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
972 * good tags like \<i\> will be dropped entirely.
974 * @param string|Message $name
976 public function setPageTitle( $name ) {
977 if ( $name instanceof Message
) {
978 $name = $name->setContext( $this->getContext() )->text();
981 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
982 # but leave "<i>foobar</i>" alone
983 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
984 $this->mPagetitle
= $nameWithTags;
986 # change "<i>foo&bar</i>" to "foo&bar"
988 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
989 ->inContentLanguage()
994 * Return the "page title", i.e. the content of the \<h1\> tag.
998 public function getPageTitle() {
999 return $this->mPagetitle
;
1003 * Set the Title object to use
1007 public function setTitle( Title
$t ) {
1008 $this->getContext()->setTitle( $t );
1012 * Replace the subtitle with $str
1014 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1016 public function setSubtitle( $str ) {
1017 $this->clearSubtitle();
1018 $this->addSubtitle( $str );
1022 * Add $str to the subtitle
1024 * @deprecated since 1.19; use addSubtitle() instead
1025 * @param string|Message $str String or Message to add to the subtitle
1027 public function appendSubtitle( $str ) {
1028 $this->addSubtitle( $str );
1032 * Add $str to the subtitle
1034 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1036 public function addSubtitle( $str ) {
1037 if ( $str instanceof Message
) {
1038 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1040 $this->mSubtitle
[] = $str;
1045 * Build message object for a subtitle containing a backlink to a page
1047 * @param Title $title Title to link to
1048 * @param array $query Array of additional parameters to include in the link
1052 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1053 if ( $title->isRedirect() ) {
1054 $query['redirect'] = 'no';
1056 return wfMessage( 'backlinksubtitle' )
1057 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1061 * Add a subtitle containing a backlink to a page
1063 * @param Title $title Title to link to
1064 * @param array $query Array of additional parameters to include in the link
1066 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1067 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1071 * Clear the subtitles
1073 public function clearSubtitle() {
1074 $this->mSubtitle
= array();
1082 public function getSubtitle() {
1083 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1087 * Set the page as printable, i.e. it'll be displayed with all
1088 * print styles included
1090 public function setPrintable() {
1091 $this->mPrintable
= true;
1095 * Return whether the page is "printable"
1099 public function isPrintable() {
1100 return $this->mPrintable
;
1104 * Disable output completely, i.e. calling output() will have no effect
1106 public function disable() {
1107 $this->mDoNothing
= true;
1111 * Return whether the output will be completely disabled
1115 public function isDisabled() {
1116 return $this->mDoNothing
;
1120 * Show an "add new section" link?
1124 public function showNewSectionLink() {
1125 return $this->mNewSectionLink
;
1129 * Forcibly hide the new section link?
1133 public function forceHideNewSectionLink() {
1134 return $this->mHideNewSectionLink
;
1138 * Add or remove feed links in the page header
1139 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1140 * for the new version
1141 * @see addFeedLink()
1143 * @param bool $show True: add default feeds, false: remove all feeds
1145 public function setSyndicated( $show = true ) {
1147 $this->setFeedAppendQuery( false );
1149 $this->mFeedLinks
= array();
1154 * Add default feeds to the page header
1155 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1156 * for the new version
1157 * @see addFeedLink()
1159 * @param string $val Query to append to feed links or false to output
1162 public function setFeedAppendQuery( $val ) {
1163 $this->mFeedLinks
= array();
1165 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1166 $query = "feed=$type";
1167 if ( is_string( $val ) ) {
1168 $query .= '&' . $val;
1170 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1175 * Add a feed link to the page header
1177 * @param string $format Feed type, should be a key of $wgFeedClasses
1178 * @param string $href URL
1180 public function addFeedLink( $format, $href ) {
1181 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1182 $this->mFeedLinks
[$format] = $href;
1187 * Should we output feed links for this page?
1190 public function isSyndicated() {
1191 return count( $this->mFeedLinks
) > 0;
1195 * Return URLs for each supported syndication format for this page.
1196 * @return array Associating format keys with URLs
1198 public function getSyndicationLinks() {
1199 return $this->mFeedLinks
;
1203 * Will currently always return null
1207 public function getFeedAppendQuery() {
1208 return $this->mFeedLinksAppendQuery
;
1212 * Set whether the displayed content is related to the source of the
1213 * corresponding article on the wiki
1214 * Setting true will cause the change "article related" toggle to true
1218 public function setArticleFlag( $v ) {
1219 $this->mIsarticle
= $v;
1221 $this->mIsArticleRelated
= $v;
1226 * Return whether the content displayed page is related to the source of
1227 * the corresponding article on the wiki
1231 public function isArticle() {
1232 return $this->mIsarticle
;
1236 * Set whether this page is related an article on the wiki
1237 * Setting false will cause the change of "article flag" toggle to false
1241 public function setArticleRelated( $v ) {
1242 $this->mIsArticleRelated
= $v;
1244 $this->mIsarticle
= false;
1249 * Return whether this page is related an article on the wiki
1253 public function isArticleRelated() {
1254 return $this->mIsArticleRelated
;
1258 * Add new language links
1260 * @param array $newLinkArray Associative array mapping language code to the page
1263 public function addLanguageLinks( array $newLinkArray ) {
1264 $this->mLanguageLinks +
= $newLinkArray;
1268 * Reset the language links and add new language links
1270 * @param array $newLinkArray Associative array mapping language code to the page
1273 public function setLanguageLinks( array $newLinkArray ) {
1274 $this->mLanguageLinks
= $newLinkArray;
1278 * Get the list of language links
1280 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1282 public function getLanguageLinks() {
1283 return $this->mLanguageLinks
;
1287 * Add an array of categories, with names in the keys
1289 * @param array $categories Mapping category name => sort key
1291 public function addCategoryLinks( array $categories ) {
1294 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1298 # Add the links to a LinkBatch
1299 $arr = array( NS_CATEGORY
=> $categories );
1300 $lb = new LinkBatch
;
1301 $lb->setArray( $arr );
1303 # Fetch existence plus the hiddencat property
1304 $dbr = wfGetDB( DB_SLAVE
);
1305 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1306 'page_is_redirect', 'page_latest', 'pp_value' );
1308 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1309 $fields[] = 'page_content_model';
1312 $res = $dbr->select( array( 'page', 'page_props' ),
1314 $lb->constructSet( 'page', $dbr ),
1317 array( 'page_props' => array( 'LEFT JOIN', array(
1318 'pp_propname' => 'hiddencat',
1323 # Add the results to the link cache
1324 $lb->addResultToCache( LinkCache
::singleton(), $res );
1326 # Set all the values to 'normal'.
1327 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1329 # Mark hidden categories
1330 foreach ( $res as $row ) {
1331 if ( isset( $row->pp_value
) ) {
1332 $categories[$row->page_title
] = 'hidden';
1336 # Add the remaining categories to the skin
1338 'OutputPageMakeCategoryLinks',
1339 array( &$this, $categories, &$this->mCategoryLinks
) )
1341 foreach ( $categories as $category => $type ) {
1342 $origcategory = $category;
1343 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1347 $wgContLang->findVariantLink( $category, $title, true );
1348 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1351 $text = $wgContLang->convertHtml( $title->getText() );
1352 $this->mCategories
[] = $title->getText();
1353 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1359 * Reset the category links (but not the category list) and add $categories
1361 * @param array $categories Mapping category name => sort key
1363 public function setCategoryLinks( array $categories ) {
1364 $this->mCategoryLinks
= array();
1365 $this->addCategoryLinks( $categories );
1369 * Get the list of category links, in a 2-D array with the following format:
1370 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1371 * hidden categories) and $link a HTML fragment with a link to the category
1376 public function getCategoryLinks() {
1377 return $this->mCategoryLinks
;
1381 * Get the list of category names this page belongs to
1383 * @return array Array of strings
1385 public function getCategories() {
1386 return $this->mCategories
;
1390 * Add an array of indicators, with their identifiers as array
1391 * keys and HTML contents as values.
1393 * In case of duplicate keys, existing values are overwritten.
1395 * @param array $indicators
1398 public function setIndicators( array $indicators ) {
1399 $this->mIndicators
= $indicators +
$this->mIndicators
;
1400 // Keep ordered by key
1401 ksort( $this->mIndicators
);
1405 * Get the indicators associated with this page.
1407 * The array will be internally ordered by item keys.
1409 * @return array Keys: identifiers, values: HTML contents
1412 public function getIndicators() {
1413 return $this->mIndicators
;
1417 * Adds help link with an icon via page indicators.
1418 * Link target can be overridden by a local message containing a wikilink:
1419 * the message key is: lowercase action or special page name + '-helppage'.
1420 * @param string $to Target MediaWiki.org page title or encoded URL.
1421 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1424 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1425 $this->addModuleStyles( 'mediawiki.helplink' );
1426 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1428 if ( $overrideBaseUrl ) {
1431 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1432 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1435 $link = Html
::rawElement(
1439 'target' => '_blank',
1440 'class' => 'mw-helplink',
1445 $this->setIndicators( array( 'mw-helplink' => $link ) );
1449 * Do not allow scripts which can be modified by wiki users to load on this page;
1450 * only allow scripts bundled with, or generated by, the software.
1451 * Site-wide styles are controlled by a config setting, since they can be
1452 * used to create a custom skin/theme, but not user-specific ones.
1454 * @todo this should be given a more accurate name
1456 public function disallowUserJs() {
1457 $this->reduceAllowedModules(
1458 ResourceLoaderModule
::TYPE_SCRIPTS
,
1459 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1462 // Site-wide styles are controlled by a config setting, see bug 71621
1463 // for background on why. User styles are never allowed.
1464 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1465 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1467 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1469 $this->reduceAllowedModules(
1470 ResourceLoaderModule
::TYPE_STYLES
,
1476 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1477 * @see ResourceLoaderModule::$origin
1478 * @param string $type ResourceLoaderModule TYPE_ constant
1479 * @return int ResourceLoaderModule ORIGIN_ class constant
1481 public function getAllowedModules( $type ) {
1482 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1483 return min( array_values( $this->mAllowedModules
) );
1485 return isset( $this->mAllowedModules
[$type] )
1486 ?
$this->mAllowedModules
[$type]
1487 : ResourceLoaderModule
::ORIGIN_ALL
;
1492 * Set the highest level of CSS/JS untrustworthiness allowed
1494 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1495 * Use reduceAllowedModules() instead
1496 * @param string $type ResourceLoaderModule TYPE_ constant
1497 * @param int $level ResourceLoaderModule class constant
1499 public function setAllowedModules( $type, $level ) {
1500 wfDeprecated( __METHOD__
, '1.24' );
1501 $this->reduceAllowedModules( $type, $level );
1505 * Limit the highest level of CSS/JS untrustworthiness allowed.
1507 * If passed the same or a higher level than the current level of untrustworthiness set, the
1508 * level will remain unchanged.
1510 * @param string $type
1511 * @param int $level ResourceLoaderModule class constant
1513 public function reduceAllowedModules( $type, $level ) {
1514 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1518 * Prepend $text to the body HTML
1520 * @param string $text HTML
1522 public function prependHTML( $text ) {
1523 $this->mBodytext
= $text . $this->mBodytext
;
1527 * Append $text to the body HTML
1529 * @param string $text HTML
1531 public function addHTML( $text ) {
1532 $this->mBodytext
.= $text;
1536 * Shortcut for adding an Html::element via addHTML.
1540 * @param string $element
1541 * @param array $attribs
1542 * @param string $contents
1544 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1545 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1549 * Clear the body HTML
1551 public function clearHTML() {
1552 $this->mBodytext
= '';
1558 * @return string HTML
1560 public function getHTML() {
1561 return $this->mBodytext
;
1565 * Get/set the ParserOptions object to use for wikitext parsing
1567 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1568 * current ParserOption object
1569 * @return ParserOptions
1571 public function parserOptions( $options = null ) {
1572 if ( !$this->mParserOptions
) {
1573 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1574 $this->mParserOptions
->setEditSection( false );
1576 return wfSetVar( $this->mParserOptions
, $options );
1580 * Set the revision ID which will be seen by the wiki text parser
1581 * for things such as embedded {{REVISIONID}} variable use.
1583 * @param int|null $revid An positive integer, or null
1584 * @return mixed Previous value
1586 public function setRevisionId( $revid ) {
1587 $val = is_null( $revid ) ?
null : intval( $revid );
1588 return wfSetVar( $this->mRevisionId
, $val );
1592 * Get the displayed revision ID
1596 public function getRevisionId() {
1597 return $this->mRevisionId
;
1601 * Set the timestamp of the revision which will be displayed. This is used
1602 * to avoid a extra DB call in Skin::lastModified().
1604 * @param string|null $timestamp
1605 * @return mixed Previous value
1607 public function setRevisionTimestamp( $timestamp ) {
1608 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1612 * Get the timestamp of displayed revision.
1613 * This will be null if not filled by setRevisionTimestamp().
1615 * @return string|null
1617 public function getRevisionTimestamp() {
1618 return $this->mRevisionTimestamp
;
1622 * Set the displayed file version
1624 * @param File|bool $file
1625 * @return mixed Previous value
1627 public function setFileVersion( $file ) {
1629 if ( $file instanceof File
&& $file->exists() ) {
1630 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1632 return wfSetVar( $this->mFileVersion
, $val, true );
1636 * Get the displayed file version
1638 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1640 public function getFileVersion() {
1641 return $this->mFileVersion
;
1645 * Get the templates used on this page
1647 * @return array (namespace => dbKey => revId)
1650 public function getTemplateIds() {
1651 return $this->mTemplateIds
;
1655 * Get the files used on this page
1657 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1660 public function getFileSearchOptions() {
1661 return $this->mImageTimeKeys
;
1665 * Convert wikitext to HTML and add it to the buffer
1666 * Default assumes that the current page title will be used.
1668 * @param string $text
1669 * @param bool $linestart Is this the start of a line?
1670 * @param bool $interface Is this text in the user interface language?
1671 * @throws MWException
1673 public function addWikiText( $text, $linestart = true, $interface = true ) {
1674 $title = $this->getTitle(); // Work around E_STRICT
1676 throw new MWException( 'Title is null' );
1678 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1682 * Add wikitext with a custom Title object
1684 * @param string $text Wikitext
1685 * @param Title $title
1686 * @param bool $linestart Is this the start of a line?
1688 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1689 $this->addWikiTextTitle( $text, $title, $linestart );
1693 * Add wikitext with a custom Title object and tidy enabled.
1695 * @param string $text Wikitext
1696 * @param Title $title
1697 * @param bool $linestart Is this the start of a line?
1699 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1700 $this->addWikiTextTitle( $text, $title, $linestart, true );
1704 * Add wikitext with tidy enabled
1706 * @param string $text Wikitext
1707 * @param bool $linestart Is this the start of a line?
1709 public function addWikiTextTidy( $text, $linestart = true ) {
1710 $title = $this->getTitle();
1711 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1715 * Add wikitext with a custom Title object
1717 * @param string $text Wikitext
1718 * @param Title $title
1719 * @param bool $linestart Is this the start of a line?
1720 * @param bool $tidy Whether to use tidy
1721 * @param bool $interface Whether it is an interface message
1722 * (for example disables conversion)
1724 public function addWikiTextTitle( $text, Title
$title, $linestart,
1725 $tidy = false, $interface = false
1729 $popts = $this->parserOptions();
1730 $oldTidy = $popts->setTidy( $tidy );
1731 $popts->setInterfaceMessage( (bool)$interface );
1733 $parserOutput = $wgParser->getFreshParser()->parse(
1734 $text, $title, $popts,
1735 $linestart, true, $this->mRevisionId
1738 $popts->setTidy( $oldTidy );
1740 $this->addParserOutput( $parserOutput );
1745 * Add a ParserOutput object, but without Html.
1747 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1748 * @param ParserOutput $parserOutput
1750 public function addParserOutputNoText( $parserOutput ) {
1751 $this->addParserOutputMetadata( $parserOutput );
1755 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1756 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1760 * @param ParserOutput $parserOutput
1762 public function addParserOutputMetadata( $parserOutput ) {
1763 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1764 $this->addCategoryLinks( $parserOutput->getCategories() );
1765 $this->setIndicators( $parserOutput->getIndicators() );
1766 $this->mNewSectionLink
= $parserOutput->getNewSection();
1767 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1769 $this->mParseWarnings
= $parserOutput->getWarnings();
1770 if ( !$parserOutput->isCacheable() ) {
1771 $this->enableClientCache( false );
1773 $this->mNoGallery
= $parserOutput->getNoGallery();
1774 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1775 $this->addModules( $parserOutput->getModules() );
1776 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1777 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1778 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1779 $this->mPreventClickjacking
= $this->mPreventClickjacking
1780 ||
$parserOutput->preventClickjacking();
1782 // Template versioning...
1783 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1784 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1785 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1787 $this->mTemplateIds
[$ns] = $dbks;
1790 // File versioning...
1791 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1792 $this->mImageTimeKeys
[$dbk] = $data;
1795 // Hooks registered in the object
1796 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1797 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1798 list( $hookName, $data ) = $hookInfo;
1799 if ( isset( $parserOutputHooks[$hookName] ) ) {
1800 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1804 // enable OOUI if requested via ParserOutput
1805 if ( $parserOutput->getEnableOOUI() ) {
1806 $this->enableOOUI();
1809 // Link flags are ignored for now, but may in the future be
1810 // used to mark individual language links.
1811 $linkFlags = array();
1812 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1813 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1817 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1818 * ParserOutput object, without any other metadata.
1821 * @param ParserOutput $parserOutput
1823 public function addParserOutputContent( $parserOutput ) {
1824 $this->addParserOutputText( $parserOutput );
1826 $this->addModules( $parserOutput->getModules() );
1827 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1828 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1830 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1834 * Add the HTML associated with a ParserOutput object, without any metadata.
1837 * @param ParserOutput $parserOutput
1839 public function addParserOutputText( $parserOutput ) {
1840 $text = $parserOutput->getText();
1841 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1842 $this->addHTML( $text );
1846 * Add everything from a ParserOutput object.
1848 * @param ParserOutput $parserOutput
1850 function addParserOutput( $parserOutput ) {
1851 $this->addParserOutputMetadata( $parserOutput );
1852 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1854 // Touch section edit links only if not previously disabled
1855 if ( $parserOutput->getEditSectionTokens() ) {
1856 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1859 $this->addParserOutputText( $parserOutput );
1863 * Add the output of a QuickTemplate to the output buffer
1865 * @param QuickTemplate $template
1867 public function addTemplate( &$template ) {
1868 $this->addHTML( $template->getHTML() );
1872 * Parse wikitext and return the HTML.
1874 * @param string $text
1875 * @param bool $linestart Is this the start of a line?
1876 * @param bool $interface Use interface language ($wgLang instead of
1877 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1878 * This also disables LanguageConverter.
1879 * @param Language $language Target language object, will override $interface
1880 * @throws MWException
1881 * @return string HTML
1883 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1886 if ( is_null( $this->getTitle() ) ) {
1887 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1890 $popts = $this->parserOptions();
1892 $popts->setInterfaceMessage( true );
1894 if ( $language !== null ) {
1895 $oldLang = $popts->setTargetLanguage( $language );
1898 $parserOutput = $wgParser->getFreshParser()->parse(
1899 $text, $this->getTitle(), $popts,
1900 $linestart, true, $this->mRevisionId
1904 $popts->setInterfaceMessage( false );
1906 if ( $language !== null ) {
1907 $popts->setTargetLanguage( $oldLang );
1910 return $parserOutput->getText();
1914 * Parse wikitext, strip paragraphs, and return the HTML.
1916 * @param string $text
1917 * @param bool $linestart Is this the start of a line?
1918 * @param bool $interface Use interface language ($wgLang instead of
1919 * $wgContLang) while parsing language sensitive magic
1920 * words like GRAMMAR and PLURAL
1921 * @return string HTML
1923 public function parseInline( $text, $linestart = true, $interface = false ) {
1924 $parsed = $this->parse( $text, $linestart, $interface );
1925 return Parser
::stripOuterParagraph( $parsed );
1929 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1931 * @param int $maxage Maximum cache time on the Squid, in seconds.
1933 public function setSquidMaxage( $maxage ) {
1934 $this->mSquidMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1938 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1940 * @param int $maxage Maximum cache time on the Squid, in seconds
1943 public function lowerCdnMaxage( $maxage ) {
1944 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1945 $this->setSquidMaxage( $this->mSquidMaxage
);
1949 * Use enableClientCache(false) to force it to send nocache headers
1951 * @param bool $state
1955 public function enableClientCache( $state ) {
1956 return wfSetVar( $this->mEnableClientCache
, $state );
1960 * Get the list of cookies that will influence on the cache
1964 function getCacheVaryCookies() {
1966 if ( $cookies === null ) {
1967 $config = $this->getConfig();
1968 $cookies = array_merge(
1970 $config->get( 'CookiePrefix' ) . 'Token',
1971 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1975 $config->get( 'CacheVaryCookies' )
1977 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1983 * Check if the request has a cache-varying cookie header
1984 * If it does, it's very important that we don't allow public caching
1988 function haveCacheVaryCookies() {
1989 $request = $this->getRequest();
1990 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
1991 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
1992 wfDebug( __METHOD__
. ": found $cookieName\n" );
1996 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2001 * Add an HTTP header that will influence on the cache
2003 * @param string $header Header name
2004 * @param string[]|null $option Options for the Key header. See
2005 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2006 * for the list of valid options.
2008 public function addVaryHeader( $header, array $option = null ) {
2009 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2010 $this->mVaryHeader
[$header] = array();
2012 if ( !is_array( $option ) ) {
2015 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2019 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2020 * such as Accept-Encoding or Cookie
2024 public function getVaryHeader() {
2025 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
2029 * Get a complete Key header
2033 public function getKeyHeader() {
2034 $cvCookies = $this->getCacheVaryCookies();
2036 $cookiesOption = array();
2037 foreach ( $cvCookies as $cookieName ) {
2038 $cookiesOption[] = 'param=' . $cookieName;
2040 $this->addVaryHeader( 'Cookie', $cookiesOption );
2043 foreach ( $this->mVaryHeader
as $header => $option ) {
2044 $newheader = $header;
2045 if ( is_array( $option ) && count( $option ) > 0 ) {
2046 $newheader .= ';' . implode( ';', $option );
2048 $headers[] = $newheader;
2050 $key = 'Key: ' . implode( ',', $headers );
2056 * T23672: Add Accept-Language to Vary and Key headers
2057 * if there's no 'variant' parameter existed in GET.
2060 * /w/index.php?title=Main_page should always be served; but
2061 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2063 function addAcceptLanguage() {
2064 $title = $this->getTitle();
2065 if ( !$title instanceof Title
) {
2069 $lang = $title->getPageLanguage();
2070 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2071 $variants = $lang->getVariants();
2072 $aloption = array();
2073 foreach ( $variants as $variant ) {
2074 if ( $variant === $lang->getCode() ) {
2077 $aloption[] = 'substr=' . $variant;
2079 // IE and some other browsers use BCP 47 standards in
2080 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2081 // We should handle these too.
2082 $variantBCP47 = wfBCP47( $variant );
2083 if ( $variantBCP47 !== $variant ) {
2084 $aloption[] = 'substr=' . $variantBCP47;
2088 $this->addVaryHeader( 'Accept-Language', $aloption );
2093 * Set a flag which will cause an X-Frame-Options header appropriate for
2094 * edit pages to be sent. The header value is controlled by
2095 * $wgEditPageFrameOptions.
2097 * This is the default for special pages. If you display a CSRF-protected
2098 * form on an ordinary view page, then you need to call this function.
2100 * @param bool $enable
2102 public function preventClickjacking( $enable = true ) {
2103 $this->mPreventClickjacking
= $enable;
2107 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2108 * This can be called from pages which do not contain any CSRF-protected
2111 public function allowClickjacking() {
2112 $this->mPreventClickjacking
= false;
2116 * Get the prevent-clickjacking flag
2121 public function getPreventClickjacking() {
2122 return $this->mPreventClickjacking
;
2126 * Get the X-Frame-Options header value (without the name part), or false
2127 * if there isn't one. This is used by Skin to determine whether to enable
2128 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2132 public function getFrameOptions() {
2133 $config = $this->getConfig();
2134 if ( $config->get( 'BreakFrames' ) ) {
2136 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2137 return $config->get( 'EditPageFrameOptions' );
2143 * Send cache control HTTP headers
2145 public function sendCacheControl() {
2146 $response = $this->getRequest()->response();
2147 $config = $this->getConfig();
2148 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2149 $response->header( "ETag: $this->mETag" );
2152 $this->addVaryHeader( 'Cookie' );
2153 $this->addAcceptLanguage();
2155 # don't serve compressed data to clients who can't handle it
2156 # maintain different caches for logged-in users and non-logged in ones
2157 $response->header( $this->getVaryHeader() );
2159 if ( $config->get( 'UseKeyHeader' ) ) {
2160 $response->header( $this->getKeyHeader() );
2163 if ( $this->mEnableClientCache
) {
2165 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2166 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2168 if ( $config->get( 'UseESI' ) ) {
2169 # We'll purge the proxy cache explicitly, but require end user agents
2170 # to revalidate against the proxy on each visit.
2171 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2172 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2173 # start with a shorter timeout for initial testing
2174 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2175 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2176 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2177 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2179 # We'll purge the proxy cache for anons explicitly, but require end user agents
2180 # to revalidate against the proxy on each visit.
2181 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2182 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2183 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2184 # start with a shorter timeout for initial testing
2185 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2186 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2187 . ', must-revalidate, max-age=0' );
2190 # We do want clients to cache if they can, but they *must* check for updates
2191 # on revisiting the page.
2192 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2193 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2194 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2196 if ( $this->mLastModified
) {
2197 $response->header( "Last-Modified: {$this->mLastModified}" );
2200 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2202 # In general, the absence of a last modified header should be enough to prevent
2203 # the client from using its cache. We send a few other things just to make sure.
2204 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2205 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2206 $response->header( 'Pragma: no-cache' );
2211 * Finally, all the text has been munged and accumulated into
2212 * the object, let's actually output it:
2214 public function output() {
2215 if ( $this->mDoNothing
) {
2219 $response = $this->getRequest()->response();
2220 $config = $this->getConfig();
2222 if ( $this->mRedirect
!= '' ) {
2223 # Standards require redirect URLs to be absolute
2224 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2226 $redirect = $this->mRedirect
;
2227 $code = $this->mRedirectCode
;
2229 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2230 if ( $code == '301' ||
$code == '303' ) {
2231 if ( !$config->get( 'DebugRedirects' ) ) {
2232 $response->statusHeader( $code );
2234 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2236 if ( $config->get( 'VaryOnXFP' ) ) {
2237 $this->addVaryHeader( 'X-Forwarded-Proto' );
2239 $this->sendCacheControl();
2241 $response->header( "Content-Type: text/html; charset=utf-8" );
2242 if ( $config->get( 'DebugRedirects' ) ) {
2243 $url = htmlspecialchars( $redirect );
2244 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2245 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2246 print "</body>\n</html>\n";
2248 $response->header( 'Location: ' . $redirect );
2253 } elseif ( $this->mStatusCode
) {
2254 $response->statusHeader( $this->mStatusCode
);
2257 # Buffer output; final headers may depend on later processing
2260 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2261 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2263 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2264 // jQuery etc. can work correctly.
2265 $response->header( 'X-UA-Compatible: IE=Edge' );
2267 // Prevent framing, if requested
2268 $frameOptions = $this->getFrameOptions();
2269 if ( $frameOptions ) {
2270 $response->header( "X-Frame-Options: $frameOptions" );
2273 if ( $this->mArticleBodyOnly
) {
2274 echo $this->mBodytext
;
2276 $sk = $this->getSkin();
2277 // add skin specific modules
2278 $modules = $sk->getDefaultModules();
2280 // Enforce various default modules for all skins
2281 $coreModules = array(
2282 // Keep this list as small as possible
2284 'mediawiki.page.startup',
2288 // Support for high-density display images if enabled
2289 if ( $config->get( 'ResponsiveImages' ) ) {
2290 $coreModules[] = 'mediawiki.hidpi';
2293 $this->addModules( $coreModules );
2294 foreach ( $modules as $group ) {
2295 $this->addModules( $group );
2297 MWDebug
::addModules( $this );
2299 // Hook that allows last minute changes to the output page, e.g.
2300 // adding of CSS or Javascript by extensions.
2301 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2306 // This hook allows last minute changes to final overall output by modifying output buffer
2307 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2309 $this->sendCacheControl();
2316 * Actually output something with print.
2318 * @param string $ins The string to output
2319 * @deprecated since 1.22 Use echo yourself.
2321 public function out( $ins ) {
2322 wfDeprecated( __METHOD__
, '1.22' );
2327 * Produce a "user is blocked" page.
2328 * @deprecated since 1.18
2330 function blockedPage() {
2331 throw new UserBlockedError( $this->getUser()->mBlock
);
2335 * Prepare this object to display an error page; disable caching and
2336 * indexing, clear the current text and redirect, set the page's title
2337 * and optionally an custom HTML title (content of the "<title>" tag).
2339 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2340 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2341 * optional, if not passed the "<title>" attribute will be
2342 * based on $pageTitle
2344 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2345 $this->setPageTitle( $pageTitle );
2346 if ( $htmlTitle !== false ) {
2347 $this->setHTMLTitle( $htmlTitle );
2349 $this->setRobotPolicy( 'noindex,nofollow' );
2350 $this->setArticleRelated( false );
2351 $this->enableClientCache( false );
2352 $this->mRedirect
= '';
2353 $this->clearSubtitle();
2358 * Output a standard error page
2360 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2361 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2362 * showErrorPage( 'titlemsg', $messageObject );
2363 * showErrorPage( $titleMessageObject, $messageObject );
2365 * @param string|Message $title Message key (string) for page title, or a Message object
2366 * @param string|Message $msg Message key (string) for page text, or a Message object
2367 * @param array $params Message parameters; ignored if $msg is a Message object
2369 public function showErrorPage( $title, $msg, $params = array() ) {
2370 if ( !$title instanceof Message
) {
2371 $title = $this->msg( $title );
2374 $this->prepareErrorPage( $title );
2376 if ( $msg instanceof Message
) {
2377 if ( $params !== array() ) {
2378 trigger_error( 'Argument ignored: $params. The message parameters argument '
2379 . 'is discarded when the $msg argument is a Message object instead of '
2380 . 'a string.', E_USER_NOTICE
);
2382 $this->addHTML( $msg->parseAsBlock() );
2384 $this->addWikiMsgArray( $msg, $params );
2387 $this->returnToMain();
2391 * Output a standard permission error page
2393 * @param array $errors Error message keys
2394 * @param string $action Action that was denied or null if unknown
2396 public function showPermissionsErrorPage( array $errors, $action = null ) {
2397 // For some action (read, edit, create and upload), display a "login to do this action"
2398 // error if all of the following conditions are met:
2399 // 1. the user is not logged in
2400 // 2. the only error is insufficient permissions (i.e. no block or something else)
2401 // 3. the error can be avoided simply by logging in
2402 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2403 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2404 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2405 && ( User
::groupHasPermission( 'user', $action )
2406 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2408 $displayReturnto = null;
2410 # Due to bug 32276, if a user does not have read permissions,
2411 # $this->getTitle() will just give Special:Badtitle, which is
2412 # not especially useful as a returnto parameter. Use the title
2413 # from the request instead, if there was one.
2414 $request = $this->getRequest();
2415 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2416 if ( $action == 'edit' ) {
2417 $msg = 'whitelistedittext';
2418 $displayReturnto = $returnto;
2419 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2420 $msg = 'nocreatetext';
2421 } elseif ( $action == 'upload' ) {
2422 $msg = 'uploadnologintext';
2424 $msg = 'loginreqpagetext';
2425 $displayReturnto = Title
::newMainPage();
2431 $query['returnto'] = $returnto->getPrefixedText();
2433 if ( !$request->wasPosted() ) {
2434 $returntoquery = $request->getValues();
2435 unset( $returntoquery['title'] );
2436 unset( $returntoquery['returnto'] );
2437 unset( $returntoquery['returntoquery'] );
2438 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2441 $loginLink = Linker
::linkKnown(
2442 SpecialPage
::getTitleFor( 'Userlogin' ),
2443 $this->msg( 'loginreqlink' )->escaped(),
2448 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2449 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2451 # Don't return to a page the user can't read otherwise
2452 # we'll end up in a pointless loop
2453 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2454 $this->returnToMain( null, $displayReturnto );
2457 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2458 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2463 * Display an error page indicating that a given version of MediaWiki is
2464 * required to use it
2466 * @param mixed $version The version of MediaWiki needed to use the page
2468 public function versionRequired( $version ) {
2469 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2471 $this->addWikiMsg( 'versionrequiredtext', $version );
2472 $this->returnToMain();
2476 * Display an error page noting that a given permission bit is required.
2477 * @deprecated since 1.18, just throw the exception directly
2478 * @param string $permission Key required
2479 * @throws PermissionsError
2481 public function permissionRequired( $permission ) {
2482 throw new PermissionsError( $permission );
2486 * Produce the stock "please login to use the wiki" page
2488 * @deprecated since 1.19; throw the exception directly
2490 public function loginToUse() {
2491 throw new PermissionsError( 'read' );
2495 * Format a list of error messages
2497 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2498 * @param string $action Action that was denied or null if unknown
2499 * @return string The wikitext error-messages, formatted into a list.
2501 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2502 if ( $action == null ) {
2503 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2505 $action_desc = $this->msg( "action-$action" )->plain();
2507 'permissionserrorstext-withaction',
2510 )->plain() . "\n\n";
2513 if ( count( $errors ) > 1 ) {
2514 $text .= '<ul class="permissions-errors">' . "\n";
2516 foreach ( $errors as $error ) {
2518 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2523 $text .= "<div class=\"permissions-errors\">\n" .
2524 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2532 * Display a page stating that the Wiki is in read-only mode.
2533 * Should only be called after wfReadOnly() has returned true.
2535 * Historically, this function was used to show the source of the page that the user
2536 * was trying to edit and _also_ permissions error messages. The relevant code was
2537 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2539 * @deprecated since 1.25; throw the exception directly
2540 * @throws ReadOnlyError
2542 public function readOnlyPage() {
2543 if ( func_num_args() > 0 ) {
2544 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2547 throw new ReadOnlyError
;
2551 * Turn off regular page output and return an error response
2552 * for when rate limiting has triggered.
2554 * @deprecated since 1.25; throw the exception directly
2556 public function rateLimited() {
2557 wfDeprecated( __METHOD__
, '1.25' );
2558 throw new ThrottledError
;
2562 * Show a warning about slave lag
2564 * If the lag is higher than $wgSlaveLagCritical seconds,
2565 * then the warning is a bit more obvious. If the lag is
2566 * lower than $wgSlaveLagWarning, then no warning is shown.
2568 * @param int $lag Slave lag
2570 public function showLagWarning( $lag ) {
2571 $config = $this->getConfig();
2572 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2573 $message = $lag < $config->get( 'SlaveLagCritical' )
2576 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2577 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2581 public function showFatalError( $message ) {
2582 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2584 $this->addHTML( $message );
2587 public function showUnexpectedValueError( $name, $val ) {
2588 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2591 public function showFileCopyError( $old, $new ) {
2592 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2595 public function showFileRenameError( $old, $new ) {
2596 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2599 public function showFileDeleteError( $name ) {
2600 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2603 public function showFileNotFoundError( $name ) {
2604 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2608 * Add a "return to" link pointing to a specified title
2610 * @param Title $title Title to link
2611 * @param array $query Query string parameters
2612 * @param string $text Text of the link (input is not escaped)
2613 * @param array $options Options array to pass to Linker
2615 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2616 $link = $this->msg( 'returnto' )->rawParams(
2617 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2618 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2622 * Add a "return to" link pointing to a specified title,
2623 * or the title indicated in the request, or else the main page
2625 * @param mixed $unused
2626 * @param Title|string $returnto Title or String to return to
2627 * @param string $returntoquery Query string for the return to link
2629 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2630 if ( $returnto == null ) {
2631 $returnto = $this->getRequest()->getText( 'returnto' );
2634 if ( $returntoquery == null ) {
2635 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2638 if ( $returnto === '' ) {
2639 $returnto = Title
::newMainPage();
2642 if ( is_object( $returnto ) ) {
2643 $titleObj = $returnto;
2645 $titleObj = Title
::newFromText( $returnto );
2647 if ( !is_object( $titleObj ) ) {
2648 $titleObj = Title
::newMainPage();
2651 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2655 * @param Skin $sk The given Skin
2656 * @param bool $includeStyle Unused
2657 * @return string The doctype, opening "<html>", and head element.
2659 public function headElement( Skin
$sk, $includeStyle = true ) {
2662 $userdir = $this->getLanguage()->getDir();
2663 $sitedir = $wgContLang->getDir();
2665 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2667 if ( $this->getHTMLTitle() == '' ) {
2668 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2671 $openHead = Html
::openElement( 'head' );
2673 # Don't bother with the newline if $head == ''
2674 $ret .= "$openHead\n";
2677 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2678 // Add <meta charset="UTF-8">
2679 // This should be before <title> since it defines the charset used by
2680 // text including the text inside <title>.
2681 // The spec recommends defining XHTML5's charset using the XML declaration
2683 // Our XML declaration is output by Html::htmlHeader.
2684 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2685 // http://www.whatwg.org/html/semantics.html#charset
2686 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2689 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2690 $ret .= $this->getInlineHeadScripts() . "\n";
2691 $ret .= $this->buildCssLinks() . "\n";
2692 $ret .= $this->getExternalHeadScripts() . "\n";
2694 foreach ( $this->getHeadLinksArray() as $item ) {
2695 $ret .= $item . "\n";
2698 foreach ( $this->mHeadItems
as $item ) {
2699 $ret .= $item . "\n";
2702 $closeHead = Html
::closeElement( 'head' );
2704 $ret .= "$closeHead\n";
2707 $bodyClasses = array();
2708 $bodyClasses[] = 'mediawiki';
2710 # Classes for LTR/RTL directionality support
2711 $bodyClasses[] = $userdir;
2712 $bodyClasses[] = "sitedir-$sitedir";
2714 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2715 # A <body> class is probably not the best way to do this . . .
2716 $bodyClasses[] = 'capitalize-all-nouns';
2719 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2720 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2722 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2724 $bodyAttrs = array();
2725 // While the implode() is not strictly needed, it's used for backwards compatibility
2726 // (this used to be built as a string and hooks likely still expect that).
2727 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2729 // Allow skins and extensions to add body attributes they need
2730 $sk->addToBodyAttributes( $this, $bodyAttrs );
2731 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2733 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2739 * Get a ResourceLoader object associated with this OutputPage
2741 * @return ResourceLoader
2743 public function getResourceLoader() {
2744 if ( is_null( $this->mResourceLoader
) ) {
2745 $this->mResourceLoader
= new ResourceLoader(
2747 LoggerFactory
::getInstance( 'resourceloader' )
2750 return $this->mResourceLoader
;
2754 * Construct neccecary html and loader preset states to load modules on a page.
2756 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2758 * @param array|string $modules One or more module names
2759 * @param string $only ResourceLoaderModule TYPE_ class constant
2760 * @param array $extraQuery [optional] Array with extra query parameters for the request
2761 * @return array A list of HTML strings and array of client loader preset states
2763 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = array() ) {
2764 $modules = (array)$modules;
2767 // List of html strings
2769 // Associative array of module names and their states
2770 'states' => array(),
2773 if ( !count( $modules ) ) {
2777 if ( count( $modules ) > 1 ) {
2778 // Remove duplicate module requests
2779 $modules = array_unique( $modules );
2780 // Sort module names so requests are more uniform
2783 if ( ResourceLoader
::inDebugMode() ) {
2784 // Recursively call us for every item
2785 foreach ( $modules as $name ) {
2786 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2787 $links['html'] = array_merge( $links['html'], $link['html'] );
2788 $links['states'] +
= $link['states'];
2794 if ( !is_null( $this->mTarget
) ) {
2795 $extraQuery['target'] = $this->mTarget
;
2798 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2799 $sortedModules = array();
2800 $resourceLoader = $this->getResourceLoader();
2801 foreach ( $modules as $name ) {
2802 $module = $resourceLoader->getModule( $name );
2803 # Check that we're allowed to include this module on this page
2805 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2806 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2807 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2808 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2809 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2810 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2811 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2816 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2819 foreach ( $sortedModules as $source => $groups ) {
2820 foreach ( $groups as $group => $grpModules ) {
2821 // Special handling for user-specific groups
2823 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2824 $user = $this->getUser()->getName();
2827 // Create a fake request based on the one we are about to make so modules return
2828 // correct timestamp and emptiness data
2829 $query = ResourceLoader
::makeLoaderQuery(
2830 array(), // modules; not determined yet
2831 $this->getLanguage()->getCode(),
2832 $this->getSkin()->getSkinName(),
2834 null, // version; not determined yet
2835 ResourceLoader
::inDebugMode(),
2836 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2837 $this->isPrintable(),
2838 $this->getRequest()->getBool( 'handheld' ),
2841 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2843 // Extract modules that know they're empty and see if we have one or more
2846 foreach ( $grpModules as $key => $module ) {
2847 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2848 // If we're only getting the styles, we don't need to do anything for empty modules.
2849 if ( $module->isKnownEmpty( $context ) ) {
2850 unset( $grpModules[$key] );
2851 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2852 $links['states'][$key] = 'ready';
2856 $isRaw |
= $module->isRaw();
2859 // If there are no non-empty modules, skip this group
2860 if ( count( $grpModules ) === 0 ) {
2864 // Inline private modules. These can't be loaded through load.php for security
2865 // reasons, see bug 34907. Note that these modules should be loaded from
2866 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2867 // properly use them as dependencies (bug 30914)
2868 if ( $group === 'private' ) {
2869 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2870 $links['html'][] = Html
::inlineStyle(
2871 $resourceLoader->makeModuleResponse( $context, $grpModules )
2874 $links['html'][] = ResourceLoader
::makeInlineScript(
2875 $resourceLoader->makeModuleResponse( $context, $grpModules )
2881 // Special handling for the user group; because users might change their stuff
2882 // on-wiki like user pages, or user preferences; we need to find the highest
2883 // timestamp of these user-changeable modules so we can ensure cache misses on change
2884 // This should NOT be done for the site group (bug 27564) because anons get that too
2885 // and we shouldn't be putting timestamps in Squid-cached HTML
2887 if ( $group === 'user' ) {
2888 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2891 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2892 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2893 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2895 // Automatically select style/script elements
2896 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2897 $link = Html
::linkedStyle( $url );
2899 if ( $context->getRaw() ||
$isRaw ) {
2900 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2901 $link = Html
::element( 'script', array(
2902 // In SpecialJavaScriptTest, QUnit must load synchronous
2903 'async' => !isset( $extraQuery['sync'] ),
2907 $link = ResourceLoader
::makeInlineScript(
2908 Xml
::encodeJsCall( 'mw.loader.load', array( $url ) )
2912 // For modules requested directly in the html via <script> or mw.loader.load
2913 // tell mw.loader they are being loading to prevent duplicate requests.
2914 foreach ( $grpModules as $key => $module ) {
2915 // Don't output state=loading for the startup module.
2916 if ( $key !== 'startup' ) {
2917 $links['states'][$key] = 'loading';
2922 if ( $group == 'noscript' ) {
2923 $links['html'][] = Html
::rawElement( 'noscript', array(), $link );
2925 $links['html'][] = $link;
2934 * Build html output from an array of links from makeResourceLoaderLink.
2935 * @param array $links
2936 * @return string HTML
2938 protected static function getHtmlFromLoaderLinks( array $links ) {
2941 foreach ( $links as $link ) {
2942 if ( !is_array( $link ) ) {
2945 $html = array_merge( $html, $link['html'] );
2946 $states +
= $link['states'];
2949 // Filter out empty values
2950 $html = array_filter( $html, 'strlen' );
2952 if ( count( $states ) ) {
2953 array_unshift( $html, ResourceLoader
::makeInlineScript(
2954 ResourceLoader
::makeLoaderStateScript( $states )
2958 return WrappedString
::join( "\n", $html );
2962 * JS stuff to put in the "<head>". This is the startup module, config
2963 * vars and modules marked with position 'top'
2965 * @return string HTML fragment
2967 function getHeadScripts() {
2968 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2972 * <script src="..."> tags for "<head>". This is the startup module
2973 * and other modules marked with position 'top'.
2975 * @return string HTML fragment
2977 function getExternalHeadScripts() {
2980 // Startup - this provides the client with the module
2981 // manifest and loads jquery and mediawiki base modules
2982 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
2984 return self
::getHtmlFromLoaderLinks( $links );
2988 * <script>...</script> tags to put in "<head>".
2990 * @return string HTML fragment
2992 function getInlineHeadScripts() {
2995 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
2996 // Must be done synchronously on every page to avoid flashes of wrong content.
2997 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
2998 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
2999 // For the performance benefit of the majority, this is added unconditionally here and is
3000 // then fixed up by the startup module for unsupported browsers.
3001 $links[] = Html
::inlineScript(
3002 'document.documentElement.className = document.documentElement.className'
3003 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
3006 // Load config before anything else
3007 $links[] = ResourceLoader
::makeInlineScript(
3008 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
3011 // Load embeddable private modules before any loader links
3012 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3013 // in mw.loader.implement() calls and deferred until mw.user is available
3014 $embedScripts = array( 'user.options' );
3015 $links[] = $this->makeResourceLoaderLink(
3017 ResourceLoaderModule
::TYPE_COMBINED
3019 // Separate user.tokens as otherwise caching will be allowed (T84960)
3020 $links[] = $this->makeResourceLoaderLink(
3022 ResourceLoaderModule
::TYPE_COMBINED
3025 // Modules requests - let the client calculate dependencies and batch requests as it likes
3026 // Only load modules that have marked themselves for loading at the top
3027 $modules = $this->getModules( true, 'top' );
3029 $links[] = ResourceLoader
::makeInlineScript(
3030 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3034 // "Scripts only" modules marked for top inclusion
3035 $links[] = $this->makeResourceLoaderLink(
3036 $this->getModuleScripts( true, 'top' ),
3037 ResourceLoaderModule
::TYPE_SCRIPTS
3040 return self
::getHtmlFromLoaderLinks( $links );
3044 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3045 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3046 * site JS, and user JS.
3048 * @param bool $unused Previously used to let this method change its output based
3049 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3052 function getScriptsForBottomQueue( $unused = null ) {
3053 // Scripts "only" requests marked for bottom inclusion
3054 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3057 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3058 ResourceLoaderModule
::TYPE_SCRIPTS
3061 // Modules requests - let the client calculate dependencies and batch requests as it likes
3062 // Only load modules that have marked themselves for loading at the bottom
3063 $modules = $this->getModules( true, 'bottom' );
3065 $links[] = ResourceLoader
::makeInlineScript(
3066 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3071 $links[] = $this->mScripts
;
3073 // Add user JS if enabled
3074 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3075 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3076 if ( $this->getConfig()->get( 'AllowUserJs' )
3077 && $this->getUser()->isLoggedIn()
3078 && $this->getTitle()
3079 && $this->getTitle()->isJsSubpage()
3080 && $this->userCanPreview()
3082 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3083 // and include the draft contents as a raw script instead.
3084 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3085 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3087 // Load the previewed JS
3088 $links[] = ResourceLoader
::makeInlineScript(
3089 Xml
::encodeJsCall( 'mw.loader.using', array(
3090 array( 'user', 'site' ),
3093 . Xml
::encodeJsCall( '$.globalEval', array(
3094 $this->getRequest()->getText( 'wpTextbox1' )
3101 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3102 // asynchronously and may arrive *after* the inline script here. So the previewed code
3103 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3104 // Similarly, when previewing ./common.js and the user module does arrive first,
3105 // it will arrive without common.js and the inline script runs after.
3106 // Thus running common after the excluded subpage.
3108 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3109 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3112 // Group JS is only enabled if site JS is enabled.
3113 $links[] = $this->makeResourceLoaderLink(
3115 ResourceLoaderModule
::TYPE_COMBINED
3118 return self
::getHtmlFromLoaderLinks( $links );
3122 * JS stuff to put at the bottom of the "<body>"
3125 function getBottomScripts() {
3126 return $this->getScriptsForBottomQueue();
3130 * Get the javascript config vars to include on this page
3132 * @return array Array of javascript config vars
3135 public function getJsConfigVars() {
3136 return $this->mJsConfigVars
;
3140 * Add one or more variables to be set in mw.config in JavaScript
3142 * @param string|array $keys Key or array of key/value pairs
3143 * @param mixed $value [optional] Value of the configuration variable
3145 public function addJsConfigVars( $keys, $value = null ) {
3146 if ( is_array( $keys ) ) {
3147 foreach ( $keys as $key => $value ) {
3148 $this->mJsConfigVars
[$key] = $value;
3153 $this->mJsConfigVars
[$keys] = $value;
3157 * Get an array containing the variables to be set in mw.config in JavaScript.
3159 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3160 * - in other words, page-independent/site-wide variables (without state).
3161 * You will only be adding bloat to the html page and causing page caches to
3162 * have to be purged on configuration changes.
3165 public function getJSVars() {
3170 $canonicalSpecialPageName = false; # bug 21115
3172 $title = $this->getTitle();
3173 $ns = $title->getNamespace();
3174 $canonicalNamespace = MWNamespace
::exists( $ns )
3175 ? MWNamespace
::getCanonicalName( $ns )
3176 : $title->getNsText();
3178 $sk = $this->getSkin();
3179 // Get the relevant title so that AJAX features can use the correct page name
3180 // when making API requests from certain special pages (bug 34972).
3181 $relevantTitle = $sk->getRelevantTitle();
3182 $relevantUser = $sk->getRelevantUser();
3184 if ( $ns == NS_SPECIAL
) {
3185 list( $canonicalSpecialPageName, /*...*/ ) =
3186 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3187 } elseif ( $this->canUseWikiPage() ) {
3188 $wikiPage = $this->getWikiPage();
3189 $curRevisionId = $wikiPage->getLatest();
3190 $articleId = $wikiPage->getId();
3193 $lang = $title->getPageLanguage();
3195 // Pre-process information
3196 $separatorTransTable = $lang->separatorTransformTable();
3197 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3198 $compactSeparatorTransTable = array(
3199 implode( "\t", array_keys( $separatorTransTable ) ),
3200 implode( "\t", $separatorTransTable ),
3202 $digitTransTable = $lang->digitTransformTable();
3203 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3204 $compactDigitTransTable = array(
3205 implode( "\t", array_keys( $digitTransTable ) ),
3206 implode( "\t", $digitTransTable ),
3209 $user = $this->getUser();
3212 'wgCanonicalNamespace' => $canonicalNamespace,
3213 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3214 'wgNamespaceNumber' => $title->getNamespace(),
3215 'wgPageName' => $title->getPrefixedDBkey(),
3216 'wgTitle' => $title->getText(),
3217 'wgCurRevisionId' => $curRevisionId,
3218 'wgRevisionId' => (int)$this->getRevisionId(),
3219 'wgArticleId' => $articleId,
3220 'wgIsArticle' => $this->isArticle(),
3221 'wgIsRedirect' => $title->isRedirect(),
3222 'wgAction' => Action
::getActionName( $this->getContext() ),
3223 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3224 'wgUserGroups' => $user->getEffectiveGroups(),
3225 'wgCategories' => $this->getCategories(),
3226 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3227 'wgPageContentLanguage' => $lang->getCode(),
3228 'wgPageContentModel' => $title->getContentModel(),
3229 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3230 'wgDigitTransformTable' => $compactDigitTransTable,
3231 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3232 'wgMonthNames' => $lang->getMonthNamesArray(),
3233 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3234 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3235 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3238 if ( $user->isLoggedIn() ) {
3239 $vars['wgUserId'] = $user->getId();
3240 $vars['wgUserEditCount'] = $user->getEditCount();
3241 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3242 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3243 // Get the revision ID of the oldest new message on the user's talk
3244 // page. This can be used for constructing new message alerts on
3246 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3249 if ( $wgContLang->hasVariants() ) {
3250 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3252 // Same test as SkinTemplate
3253 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3254 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3256 foreach ( $title->getRestrictionTypes() as $type ) {
3257 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3260 if ( $title->isMainPage() ) {
3261 $vars['wgIsMainPage'] = true;
3264 if ( $this->mRedirectedFrom
) {
3265 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3268 if ( $relevantUser ) {
3269 $vars['wgRelevantUserName'] = $relevantUser->getName();
3272 // Allow extensions to add their custom variables to the mw.config map.
3273 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3274 // page-dependant but site-wide (without state).
3275 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3276 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3278 // Merge in variables from addJsConfigVars last
3279 return array_merge( $vars, $this->getJsConfigVars() );
3283 * To make it harder for someone to slip a user a fake
3284 * user-JavaScript or user-CSS preview, a random token
3285 * is associated with the login session. If it's not
3286 * passed back with the preview request, we won't render
3291 public function userCanPreview() {
3292 $request = $this->getRequest();
3293 if ( $request->getVal( 'action' ) !== 'submit' ||
!$request->wasPosted() ) {
3297 $user = $this->getUser();
3298 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3302 $title = $this->getTitle();
3303 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3306 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3307 // Don't execute another user's CSS or JS on preview (T85855)
3311 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3312 if ( count( $errors ) !== 0 ) {
3320 * @return array Array in format "link name or number => 'link html'".
3322 public function getHeadLinksArray() {
3326 $config = $this->getConfig();
3328 $canonicalUrl = $this->mCanonicalUrl
;
3330 $tags['meta-generator'] = Html
::element( 'meta', array(
3331 'name' => 'generator',
3332 'content' => "MediaWiki $wgVersion",
3335 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3336 $tags['meta-referrer'] = Html
::element( 'meta', array(
3337 'name' => 'referrer',
3338 'content' => $config->get( 'ReferrerPolicy' )
3342 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3343 if ( $p !== 'index,follow' ) {
3344 // http://www.robotstxt.org/wc/meta-user.html
3345 // Only show if it's different from the default robots policy
3346 $tags['meta-robots'] = Html
::element( 'meta', array(
3352 foreach ( $this->mMetatags
as $tag ) {
3353 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3355 $tag[0] = substr( $tag[0], 5 );
3359 $tagName = "meta-{$tag[0]}";
3360 if ( isset( $tags[$tagName] ) ) {
3361 $tagName .= $tag[1];
3363 $tags[$tagName] = Html
::element( 'meta',
3366 'content' => $tag[1]
3371 foreach ( $this->mLinktags
as $tag ) {
3372 $tags[] = Html
::element( 'link', $tag );
3375 # Universal edit button
3376 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3377 $user = $this->getUser();
3378 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3379 && ( $this->getTitle()->exists() ||
3380 $this->getTitle()->quickUserCan( 'create', $user ) )
3382 // Original UniversalEditButton
3383 $msg = $this->msg( 'edit' )->text();
3384 $tags['universal-edit-button'] = Html
::element( 'link', array(
3385 'rel' => 'alternate',
3386 'type' => 'application/x-wiki',
3388 'href' => $this->getTitle()->getEditURL(),
3390 // Alternate edit link
3391 $tags['alternative-edit'] = Html
::element( 'link', array(
3394 'href' => $this->getTitle()->getEditURL(),
3399 # Generally the order of the favicon and apple-touch-icon links
3400 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3401 # uses whichever one appears later in the HTML source. Make sure
3402 # apple-touch-icon is specified first to avoid this.
3403 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3404 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3405 'rel' => 'apple-touch-icon',
3406 'href' => $config->get( 'AppleTouchIcon' )
3410 if ( $config->get( 'Favicon' ) !== false ) {
3411 $tags['favicon'] = Html
::element( 'link', array(
3412 'rel' => 'shortcut icon',
3413 'href' => $config->get( 'Favicon' )
3417 # OpenSearch description link
3418 $tags['opensearch'] = Html
::element( 'link', array(
3420 'type' => 'application/opensearchdescription+xml',
3421 'href' => wfScript( 'opensearch_desc' ),
3422 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3425 if ( $config->get( 'EnableAPI' ) ) {
3426 # Real Simple Discovery link, provides auto-discovery information
3427 # for the MediaWiki API (and potentially additional custom API
3428 # support such as WordPress or Twitter-compatible APIs for a
3429 # blogging extension, etc)
3430 $tags['rsd'] = Html
::element( 'link', array(
3432 'type' => 'application/rsd+xml',
3433 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3434 // Whether RSD accepts relative or protocol-relative URLs is completely
3435 // undocumented, though.
3436 'href' => wfExpandUrl( wfAppendQuery(
3438 array( 'action' => 'rsd' ) ),
3445 if ( !$config->get( 'DisableLangConversion' ) ) {
3446 $lang = $this->getTitle()->getPageLanguage();
3447 if ( $lang->hasVariants() ) {
3448 $variants = $lang->getVariants();
3449 foreach ( $variants as $variant ) {
3450 $tags["variant-$variant"] = Html
::element( 'link', array(
3451 'rel' => 'alternate',
3452 'hreflang' => wfBCP47( $variant ),
3453 'href' => $this->getTitle()->getLocalURL(
3454 array( 'variant' => $variant ) )
3458 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3459 $tags["variant-x-default"] = Html
::element( 'link', array(
3460 'rel' => 'alternate',
3461 'hreflang' => 'x-default',
3462 'href' => $this->getTitle()->getLocalURL() ) );
3467 if ( $this->copyrightUrl
!== null ) {
3468 $copyright = $this->copyrightUrl
;
3471 if ( $config->get( 'RightsPage' ) ) {
3472 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3475 $copyright = $copy->getLocalURL();
3479 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3480 $copyright = $config->get( 'RightsUrl' );
3485 $tags['copyright'] = Html
::element( 'link', array(
3486 'rel' => 'copyright',
3487 'href' => $copyright )
3492 if ( $config->get( 'Feed' ) ) {
3493 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3494 # Use the page name for the title. In principle, this could
3495 # lead to issues with having the same name for different feeds
3496 # corresponding to the same page, but we can't avoid that at
3499 $tags[] = $this->feedLink(
3502 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3504 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3509 # Recent changes feed should appear on every page (except recentchanges,
3510 # that would be redundant). Put it after the per-page feed to avoid
3511 # changing existing behavior. It's still available, probably via a
3512 # menu in your browser. Some sites might have a different feed they'd
3513 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3514 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3515 # If so, use it instead.
3516 $sitename = $config->get( 'Sitename' );
3517 if ( $config->get( 'OverrideSiteFeed' ) ) {
3518 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3519 // Note, this->feedLink escapes the url.
3520 $tags[] = $this->feedLink(
3523 $this->msg( "site-{$type}-feed", $sitename )->text()
3526 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3527 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3528 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3529 $tags[] = $this->feedLink(
3531 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3532 # For grep: 'site-rss-feed', 'site-atom-feed'
3533 $this->msg( "site-{$format}-feed", $sitename )->text()
3540 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3541 if ( $canonicalUrl !== false ) {
3542 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3544 if ( $this->isArticleRelated() ) {
3545 // This affects all requests where "setArticleRelated" is true. This is
3546 // typically all requests that show content (query title, curid, oldid, diff),
3547 // and all wikipage actions (edit, delete, purge, info, history etc.).
3548 // It does not apply to File pages and Special pages.
3549 // 'history' and 'info' actions address page metadata rather than the page
3550 // content itself, so they may not be canonicalized to the view page url.
3551 // TODO: this ought to be better encapsulated in the Action class.
3552 $action = Action
::getActionName( $this->getContext() );
3553 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3554 $query = "action={$action}";
3558 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3560 $reqUrl = $this->getRequest()->getRequestURL();
3561 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3565 if ( $canonicalUrl !== false ) {
3566 $tags[] = Html
::element( 'link', array(
3567 'rel' => 'canonical',
3568 'href' => $canonicalUrl
3576 * @return string HTML tag links to be put in the header.
3577 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3578 * OutputPage::getHeadLinksArray directly.
3580 public function getHeadLinks() {
3581 wfDeprecated( __METHOD__
, '1.24' );
3582 return implode( "\n", $this->getHeadLinksArray() );
3586 * Generate a "<link rel/>" for a feed.
3588 * @param string $type Feed type
3589 * @param string $url URL to the feed
3590 * @param string $text Value of the "title" attribute
3591 * @return string HTML fragment
3593 private function feedLink( $type, $url, $text ) {
3594 return Html
::element( 'link', array(
3595 'rel' => 'alternate',
3596 'type' => "application/$type+xml",
3603 * Add a local or specified stylesheet, with the given media options.
3604 * Meant primarily for internal use...
3606 * @param string $style URL to the file
3607 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3608 * @param string $condition For IE conditional comments, specifying an IE version
3609 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3611 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3613 // Even though we expect the media type to be lowercase, but here we
3614 // force it to lowercase to be safe.
3616 $options['media'] = $media;
3619 $options['condition'] = $condition;
3622 $options['dir'] = $dir;
3624 $this->styles
[$style] = $options;
3628 * Adds inline CSS styles
3629 * @param mixed $style_css Inline CSS
3630 * @param string $flip Set to 'flip' to flip the CSS if needed
3632 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3633 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3634 # If wanted, and the interface is right-to-left, flip the CSS
3635 $style_css = CSSJanus
::transform( $style_css, true, false );
3637 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3641 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3642 * These will be applied to various media & IE conditionals.
3646 public function buildCssLinks() {
3649 $this->getSkin()->setupSkinUserCss( $this );
3651 // Add ResourceLoader styles
3652 // Split the styles into these groups
3657 'private' => array(),
3658 'noscript' => array()
3661 $otherTags = array(); // Tags to append after the normal <link> tags
3662 $resourceLoader = $this->getResourceLoader();
3664 $moduleStyles = $this->getModuleStyles();
3666 // Per-site custom styles
3667 $moduleStyles[] = 'site';
3668 $moduleStyles[] = 'noscript';
3669 $moduleStyles[] = 'user.groups';
3671 // Per-user custom styles
3672 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3673 && $this->userCanPreview()
3675 // We're on a preview of a CSS subpage
3676 // Exclude this page from the user module in case it's in there (bug 26283)
3677 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
,
3678 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3680 $otherTags = array_merge( $otherTags, $link['html'] );
3682 // Load the previewed CSS
3683 // If needed, Janus it first. This is user-supplied CSS, so it's
3684 // assumed to be right for the content language directionality.
3685 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3686 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3687 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3689 $otherTags[] = Html
::inlineStyle( $previewedCSS ) . "\n";
3691 // Load the user styles normally
3692 $moduleStyles[] = 'user';
3695 // Per-user preference styles
3696 $moduleStyles[] = 'user.cssprefs';
3698 foreach ( $moduleStyles as $name ) {
3699 $module = $resourceLoader->getModule( $name );
3703 if ( $name === 'site' ) {
3704 // HACK: The site module shouldn't be fragmented with a cache group and
3705 // http request. But in order to ensure its styles are separated and after the
3706 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3707 // The scripts remain ungrouped and rides the bottom queue.
3708 $styles['site'][] = $name;
3711 $group = $module->getGroup();
3712 // Modules in groups other than the ones needing special treatment
3713 // (see $styles assignment)
3714 // will be placed in the "other" style category.
3715 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3718 // We want site, private and user styles to override dynamically added
3719 // styles from modules, but we want dynamically added styles to override
3720 // statically added styles from other modules. So the order has to be
3721 // other, dynamic, site, private, user. Add statically added styles for
3723 $links[] = $this->makeResourceLoaderLink(
3725 ResourceLoaderModule
::TYPE_STYLES
3727 // Add normal styles added through addStyle()/addInlineStyle() here
3728 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3729 // Add marker tag to mark the place where the client-side
3730 // loader should inject dynamic styles
3731 // We use a <meta> tag with a made-up name for this because that's valid HTML
3732 $links[] = Html
::element(
3734 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3737 // Add site-specific and user-specific styles
3738 // 'private' at present only contains user.options, so put that before 'user'
3739 // Any future private modules will likely have a similar user-specific character
3740 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3741 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3742 ResourceLoaderModule
::TYPE_STYLES
3746 // Add stuff in $otherTags (previewed user CSS if applicable)
3747 return self
::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3753 public function buildCssLinksArray() {
3756 // Add any extension CSS
3757 foreach ( $this->mExtStyles
as $url ) {
3758 $this->addStyle( $url );
3760 $this->mExtStyles
= array();
3762 foreach ( $this->styles
as $file => $options ) {
3763 $link = $this->styleLink( $file, $options );
3765 $links[$file] = $link;
3772 * Generate \<link\> tags for stylesheets
3774 * @param string $style URL to the file
3775 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3776 * @return string HTML fragment
3778 protected function styleLink( $style, array $options ) {
3779 if ( isset( $options['dir'] ) ) {
3780 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3785 if ( isset( $options['media'] ) ) {
3786 $media = self
::transformCssMedia( $options['media'] );
3787 if ( is_null( $media ) ) {
3794 if ( substr( $style, 0, 1 ) == '/' ||
3795 substr( $style, 0, 5 ) == 'http:' ||
3796 substr( $style, 0, 6 ) == 'https:' ) {
3799 $config = $this->getConfig();
3800 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3801 $config->get( 'StyleVersion' );
3804 $link = Html
::linkedStyle( $url, $media );
3806 if ( isset( $options['condition'] ) ) {
3807 $condition = htmlspecialchars( $options['condition'] );
3808 $link = "<!--[if $condition]>$link<![endif]-->";
3814 * Transform "media" attribute based on request parameters
3816 * @param string $media Current value of the "media" attribute
3817 * @return string Modified value of the "media" attribute, or null to skip
3820 public static function transformCssMedia( $media ) {
3823 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3824 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3826 // Switch in on-screen display for media testing
3828 'printable' => 'print',
3829 'handheld' => 'handheld',
3831 foreach ( $switches as $switch => $targetMedia ) {
3832 if ( $wgRequest->getBool( $switch ) ) {
3833 if ( $media == $targetMedia ) {
3835 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3836 /* This regex will not attempt to understand a comma-separated media_query_list
3838 * Example supported values for $media:
3839 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3840 * Example NOT supported value for $media:
3841 * '3d-glasses, screen, print and resolution > 90dpi'
3843 * If it's a print request, we never want any kind of screen stylesheets
3844 * If it's a handheld request (currently the only other choice with a switch),
3845 * we don't want simple 'screen' but we might want screen queries that
3846 * have a max-width or something, so we'll pass all others on and let the
3847 * client do the query.
3849 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3860 * Add a wikitext-formatted message to the output.
3861 * This is equivalent to:
3863 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3865 public function addWikiMsg( /*...*/ ) {
3866 $args = func_get_args();
3867 $name = array_shift( $args );
3868 $this->addWikiMsgArray( $name, $args );
3872 * Add a wikitext-formatted message to the output.
3873 * Like addWikiMsg() except the parameters are taken as an array
3874 * instead of a variable argument list.
3876 * @param string $name
3877 * @param array $args
3879 public function addWikiMsgArray( $name, $args ) {
3880 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3884 * This function takes a number of message/argument specifications, wraps them in
3885 * some overall structure, and then parses the result and adds it to the output.
3887 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3888 * and so on. The subsequent arguments may be either
3889 * 1) strings, in which case they are message names, or
3890 * 2) arrays, in which case, within each array, the first element is the message
3891 * name, and subsequent elements are the parameters to that message.
3893 * Don't use this for messages that are not in the user's interface language.
3897 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3901 * $wgOut->addWikiText( "<div class='error'>\n"
3902 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3904 * The newline after the opening div is needed in some wikitext. See bug 19226.
3906 * @param string $wrap
3908 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3909 $msgSpecs = func_get_args();
3910 array_shift( $msgSpecs );
3911 $msgSpecs = array_values( $msgSpecs );
3913 foreach ( $msgSpecs as $n => $spec ) {
3914 if ( is_array( $spec ) ) {
3916 $name = array_shift( $args );
3917 if ( isset( $args['options'] ) ) {
3918 unset( $args['options'] );
3920 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3928 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3930 $this->addWikiText( $s );
3934 * Include jQuery core. Use this to avoid loading it multiple times
3935 * before we get a usable script loader.
3937 * @param array $modules List of jQuery modules which should be loaded
3938 * @return array The list of modules which were not loaded.
3940 * @deprecated since 1.17
3942 public function includeJQuery( array $modules = array() ) {
3947 * Enables/disables TOC, doesn't override __NOTOC__
3951 public function enableTOC( $flag = true ) {
3952 $this->mEnableTOC
= $flag;
3959 public function isTOCEnabled() {
3960 return $this->mEnableTOC
;
3964 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3968 public function enableSectionEditLinks( $flag = true ) {
3969 $this->mEnableSectionEditLinks
= $flag;
3976 public function sectionEditLinksEnabled() {
3977 return $this->mEnableSectionEditLinks
;
3981 * Helper function to setup the PHP implementation of OOUI to use in this request.
3984 * @param String $skinName The Skin name to determine the correct OOUI theme
3985 * @param String $dir Language direction
3987 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3988 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3989 // Make keys (skin names) lowercase for case-insensitive matching.
3990 $themes = array_change_key_case( $themes, CASE_LOWER
);
3991 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3992 // For example, 'OOUI\MediaWikiTheme'.
3993 $themeClass = "OOUI\\{$theme}Theme";
3994 OOUI\Theme
::setSingleton( new $themeClass() );
3995 OOUI\Element
::setDefaultDir( $dir );
3999 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4000 * MediaWiki and this OutputPage instance.
4004 public function enableOOUI() {
4006 strtolower( $this->getSkin()->getSkinName() ),
4007 $this->getLanguage()->getDir()
4009 $this->addModuleStyles( array(
4011 'oojs-ui.styles.icons',
4012 'oojs-ui.styles.indicators',
4013 'oojs-ui.styles.textures',
4014 'mediawiki.widgets.styles',