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
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 class OutputPage
extends ContextSource
{
39 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
40 protected $mMetatags = array();
43 protected $mLinktags = array();
46 protected $mCanonicalUrl = false;
49 * @var array Additional stylesheets. Looks like this is for extensions.
50 * Might be replaced by resource loader.
52 protected $mExtStyles = array();
55 * @var string Should be private - has getter and setter. Contains
57 public $mPagetitle = '';
60 * @var string Contains all of the "<body>" content. Should be private we
61 * got set/get accessors and the append() method.
63 public $mBodytext = '';
66 * Holds the debug lines that will be output as comments in page source if
67 * $wgDebugComments is enabled. See also $wgShowDebug.
68 * @deprecated since 1.20; use MWDebug class instead.
70 public $mDebugtext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = array();
97 public $mRedirect = '';
100 protected $mStatusCode;
103 * @var string Variable mLastModified and mEtag are used for sending cache control.
104 * The whole caching system should probably be moved into its own class.
106 protected $mLastModified = '';
109 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
110 * as a unique identifier for the content. It is later used by the client
111 * to compare its cached version with the server version. Client sends
112 * headers If-Match and If-None-Match containing its locally cached ETAG value.
114 * To get more information, you will have to look at HTTP/1.1 protocol which
115 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
117 private $mETag = false;
120 protected $mCategoryLinks = array();
123 protected $mCategories = array();
126 protected $mIndicators = array();
128 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
129 private $mLanguageLinks = array();
132 * Used for JavaScript (pre resource loader)
133 * @todo We should split JS / CSS.
134 * mScripts content is inserted as is in "<head>" by Skin. This might
135 * contain either a link to a stylesheet or inline CSS.
137 private $mScripts = '';
139 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
140 protected $mInlineStyles = '';
143 private $mLinkColours;
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();
154 // @todo FIXME: Next 5 variables probably come from the resource loader
157 protected $mModules = array();
160 protected $mModuleScripts = array();
163 protected $mModuleStyles = array();
166 protected $mModuleMessages = array();
168 /** @var ResourceLoader */
169 protected $mResourceLoader;
172 protected $mJsConfigVars = array();
175 protected $mTemplateIds = array();
178 protected $mImageTimeKeys = array();
181 public $mRedirectCode = '';
183 protected $mFeedLinksAppendQuery = null;
186 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
187 * @see ResourceLoaderModule::$origin
188 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
190 protected $mAllowedModules = array(
191 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
194 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
195 protected $mDoNothing = false;
203 private $mContainsOldMagic = 0;
206 protected $mContainsNewMagic = 0;
209 * lazy initialised, use parserOptions()
212 protected $mParserOptions = null;
215 * Handles the Atom / RSS links.
216 * We probably only support Atom in 2011.
217 * @see $wgAdvertisedFeedTypes
219 private $mFeedLinks = array();
221 // Gwicke work on squid caching? Roughly from 2003.
222 protected $mEnableClientCache = true;
224 /** @var bool Flag if output should only contain the body of the article. */
225 private $mArticleBodyOnly = false;
228 protected $mNewSectionLink = false;
231 protected $mHideNewSectionLink = false;
234 * @var bool Comes from the parser. This was probably made to load CSS/JS
235 * only if we had "<gallery>". Used directly in CategoryPage.php.
236 * Looks like resource loader can replace this.
238 public $mNoGallery = false;
241 private $mPageTitleActionText = '';
244 private $mParseWarnings = array();
246 /** @var int Cache stuff. Looks like mEnableClientCache */
247 protected $mSquidMaxage = 0;
253 protected $mPreventClickjacking = true;
255 /** @var int To include the variable {{REVISIONID}} */
256 private $mRevisionId = null;
259 private $mRevisionTimestamp = null;
262 protected $mFileVersion = null;
265 * @var array An array of stylesheet filenames (relative from skins path),
266 * with options for CSS media, IE conditions, and RTL/LTR direction.
267 * For internal use; add settings in the skin via $this->addStyle()
269 * Style again! This seems like a code duplication since we already have
270 * mStyles. This is what makes Open Source amazing.
272 protected $styles = array();
275 * Whether jQuery is already handled.
277 protected $mJQueryDone = false;
279 private $mIndexPolicy = 'index';
280 private $mFollowPolicy = 'follow';
281 private $mVaryHeader = array(
282 'Accept-Encoding' => array( 'list-contains=gzip' ),
286 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
291 private $mRedirectedFrom = null;
294 * Additional key => value data
296 private $mProperties = array();
299 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
301 private $mTarget = null;
304 * @var bool Whether parser output should contain table of contents
306 private $mEnableTOC = true;
309 * @var bool Whether parser output should contain section edit links
311 private $mEnableSectionEditLinks = true;
314 * Constructor for OutputPage. This should not be called directly.
315 * Instead a new RequestContext should be created and it will implicitly create
316 * a OutputPage tied to that context.
317 * @param IContextSource|null $context
319 function __construct( IContextSource
$context = null ) {
320 if ( $context === null ) {
321 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
322 wfDeprecated( __METHOD__
, '1.18' );
324 $this->setContext( $context );
329 * Redirect to $url rather than displaying the normal page
331 * @param string $url URL
332 * @param string $responsecode HTTP status code
334 public function redirect( $url, $responsecode = '302' ) {
335 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
336 $this->mRedirect
= str_replace( "\n", '', $url );
337 $this->mRedirectCode
= $responsecode;
341 * Get the URL to redirect to, or an empty string if not redirect URL set
345 public function getRedirect() {
346 return $this->mRedirect
;
350 * Set the HTTP status code to send with the output.
352 * @param int $statusCode
354 public function setStatusCode( $statusCode ) {
355 $this->mStatusCode
= $statusCode;
359 * Add a new "<meta>" tag
360 * To add an http-equiv meta tag, precede the name with "http:"
362 * @param string $name Tag name
363 * @param string $val Tag value
365 function addMeta( $name, $val ) {
366 array_push( $this->mMetatags
, array( $name, $val ) );
370 * Returns the current <meta> tags
375 public function getMetaTags() {
376 return $this->mMetatags
;
380 * Add a new \<link\> tag to the page header.
382 * Note: use setCanonicalUrl() for rel=canonical.
384 * @param array $linkarr Associative array of attributes.
386 function addLink( array $linkarr ) {
387 array_push( $this->mLinktags
, $linkarr );
391 * Returns the current <link> tags
396 public function getLinkTags() {
397 return $this->mLinktags
;
401 * Add a new \<link\> with "rel" attribute set to "meta"
403 * @param array $linkarr Associative array mapping attribute names to their
404 * values, both keys and values will be escaped, and the
405 * "rel" attribute will be automatically added
407 function addMetadataLink( array $linkarr ) {
408 $linkarr['rel'] = $this->getMetadataAttribute();
409 $this->addLink( $linkarr );
413 * Set the URL to be used for the <link rel=canonical>. This should be used
414 * in preference to addLink(), to avoid duplicate link tags.
417 function setCanonicalUrl( $url ) {
418 $this->mCanonicalUrl
= $url;
422 * Returns the URL to be used for the <link rel=canonical> if
426 * @return bool|string
428 public function getCanonicalUrl() {
429 return $this->mCanonicalUrl
;
433 * Get the value of the "rel" attribute for metadata links
437 public function getMetadataAttribute() {
438 # note: buggy CC software only reads first "meta" link
439 static $haveMeta = false;
441 return 'alternate meta';
449 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
451 * @param string $script Raw HTML
453 function addScript( $script ) {
454 $this->mScripts
.= $script . "\n";
458 * Register and add a stylesheet from an extension directory.
460 * @param string $url Path to sheet. Provide either a full url (beginning
461 * with 'http', etc) or a relative path from the document root
462 * (beginning with '/'). Otherwise it behaves identically to
463 * addStyle() and draws from the /skins folder.
465 public function addExtensionStyle( $url ) {
466 array_push( $this->mExtStyles
, $url );
470 * Get all styles added by extensions
474 function getExtStyle() {
475 return $this->mExtStyles
;
479 * Add a JavaScript file out of skins/common, or a given relative path.
481 * @param string $file Filename in skins/common or complete on-server path
483 * @param string $version Style version of the file. Defaults to $wgStyleVersion
485 public function addScriptFile( $file, $version = null ) {
486 // See if $file parameter is an absolute URL or begins with a slash
487 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
490 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
492 if ( is_null( $version ) ) {
493 $version = $this->getConfig()->get( 'StyleVersion' );
495 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
499 * Add a self-contained script tag with the given contents
501 * @param string $script JavaScript text, no "<script>" tags
503 public function addInlineScript( $script ) {
504 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
508 * Get all registered JS and CSS tags for the header.
511 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
513 function getScript() {
514 wfDeprecated( __METHOD__
, '1.24' );
515 return $this->mScripts
. $this->getHeadItems();
519 * Filter an array of modules to remove insufficiently trustworthy members, and modules
520 * which are no longer registered (eg a page is cached before an extension is disabled)
521 * @param array $modules
522 * @param string|null $position If not null, only return modules with this position
523 * @param string $type
526 protected function filterModules( array $modules, $position = null,
527 $type = ResourceLoaderModule
::TYPE_COMBINED
529 $resourceLoader = $this->getResourceLoader();
530 $filteredModules = array();
531 foreach ( $modules as $val ) {
532 $module = $resourceLoader->getModule( $val );
533 if ( $module instanceof ResourceLoaderModule
534 && $module->getOrigin() <= $this->getAllowedModules( $type )
535 && ( is_null( $position ) ||
$module->getPosition() == $position )
536 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
538 $filteredModules[] = $val;
541 return $filteredModules;
545 * Get the list of modules to include on this page
547 * @param bool $filter Whether to filter out insufficiently trustworthy modules
548 * @param string|null $position If not null, only return modules with this position
549 * @param string $param
550 * @return array Array of module names
552 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
553 $modules = array_values( array_unique( $this->$param ) );
555 ?
$this->filterModules( $modules, $position )
560 * Add one or more modules recognized by the resource loader. Modules added
561 * through this function will be loaded by the resource loader when the
564 * @param string|array $modules Module name (string) or array of module names
566 public function addModules( $modules ) {
567 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
571 * Get the list of module JS to include on this page
573 * @param bool $filter
574 * @param string|null $position
576 * @return array Array of module names
578 public function getModuleScripts( $filter = false, $position = null ) {
579 return $this->getModules( $filter, $position, 'mModuleScripts' );
583 * Add only JS of one or more modules recognized by the resource loader. Module
584 * scripts added through this function will be loaded by the resource loader when
587 * @param string|array $modules Module name (string) or array of module names
589 public function addModuleScripts( $modules ) {
590 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
594 * Get the list of module CSS to include on this page
596 * @param bool $filter
597 * @param string|null $position
599 * @return array Array of module names
601 public function getModuleStyles( $filter = false, $position = null ) {
602 return $this->getModules( $filter, $position, 'mModuleStyles' );
606 * Add only CSS of one or more modules recognized by the resource loader.
608 * Module styles added through this function will be added using standard link CSS
609 * tags, rather than as a combined Javascript and CSS package. Thus, they will
610 * load when JavaScript is disabled (unless CSS also happens to be disabled).
612 * @param string|array $modules Module name (string) or array of module names
614 public function addModuleStyles( $modules ) {
615 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
619 * Get the list of module messages to include on this page
621 * @param bool $filter
622 * @param string|null $position
624 * @return array Array of module names
626 public function getModuleMessages( $filter = false, $position = null ) {
627 return $this->getModules( $filter, $position, 'mModuleMessages' );
631 * Add only messages of one or more modules recognized by the resource loader.
632 * Module messages added through this function will be loaded by the resource
633 * loader when the page loads.
635 * @param string|array $modules Module name (string) or array of module names
637 public function addModuleMessages( $modules ) {
638 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
642 * @return null|string ResourceLoader target
644 public function getTarget() {
645 return $this->mTarget
;
649 * Sets ResourceLoader target for load.php links. If null, will be omitted
651 * @param string|null $target
653 public function setTarget( $target ) {
654 $this->mTarget
= $target;
658 * Get an array of head items
662 function getHeadItemsArray() {
663 return $this->mHeadItems
;
667 * Get all header items in a string
670 * @deprecated since 1.24 Use OutputPage::headElement or
671 * if absolutely necessary use OutputPage::getHeadItemsArray
673 function getHeadItems() {
674 wfDeprecated( __METHOD__
, '1.24' );
676 foreach ( $this->mHeadItems
as $item ) {
683 * Add or replace an header item to the output
685 * @param string $name Item name
686 * @param string $value Raw HTML
688 public function addHeadItem( $name, $value ) {
689 $this->mHeadItems
[$name] = $value;
693 * Check if the header item $name is already set
695 * @param string $name Item name
698 public function hasHeadItem( $name ) {
699 return isset( $this->mHeadItems
[$name] );
703 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
705 * @param string $tag Value of "ETag" header
707 function setETag( $tag ) {
712 * Set whether the output should only contain the body of the article,
713 * without any skin, sidebar, etc.
714 * Used e.g. when calling with "action=render".
716 * @param bool $only Whether to output only the body of the article
718 public function setArticleBodyOnly( $only ) {
719 $this->mArticleBodyOnly
= $only;
723 * Return whether the output will contain only the body of the article
727 public function getArticleBodyOnly() {
728 return $this->mArticleBodyOnly
;
732 * Set an additional output property
735 * @param string $name
736 * @param mixed $value
738 public function setProperty( $name, $value ) {
739 $this->mProperties
[$name] = $value;
743 * Get an additional output property
746 * @param string $name
747 * @return mixed Property value or null if not found
749 public function getProperty( $name ) {
750 if ( isset( $this->mProperties
[$name] ) ) {
751 return $this->mProperties
[$name];
758 * checkLastModified tells the client to use the client-cached page if
759 * possible. If successful, the OutputPage is disabled so that
760 * any future call to OutputPage->output() have no effect.
762 * Side effect: sets mLastModified for Last-Modified header
764 * @param string $timestamp
766 * @return bool True if cache-ok headers was sent.
768 public function checkLastModified( $timestamp ) {
769 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
770 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
773 $config = $this->getConfig();
774 if ( !$config->get( 'CachePages' ) ) {
775 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
779 $timestamp = wfTimestamp( TS_MW
, $timestamp );
780 $modifiedTimes = array(
781 'page' => $timestamp,
782 'user' => $this->getUser()->getTouched(),
783 'epoch' => $config->get( 'CacheEpoch' )
785 if ( $config->get( 'UseSquid' ) ) {
786 // bug 44570: the core page itself may not change, but resources might
787 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
789 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
791 $maxModified = max( $modifiedTimes );
792 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
794 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
795 if ( $clientHeader === false ) {
796 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
800 # IE sends sizes after the date like this:
801 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
802 # this breaks strtotime().
803 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
805 wfSuppressWarnings(); // E_STRICT system time bitching
806 $clientHeaderTime = strtotime( $clientHeader );
808 if ( !$clientHeaderTime ) {
810 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
813 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
817 foreach ( $modifiedTimes as $name => $value ) {
818 if ( $info !== '' ) {
821 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
824 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
825 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
826 wfDebug( __METHOD__
. ": effective Last-Modified: " .
827 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
828 if ( $clientHeaderTime < $maxModified ) {
829 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
834 # Give a 304 response code and disable body output
835 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
836 ini_set( 'zlib.output_compression', 0 );
837 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
838 $this->sendCacheControl();
841 // Don't output a compressed blob when using ob_gzhandler;
842 // it's technically against HTTP spec and seems to confuse
843 // Firefox when the response gets split over two packets.
844 wfClearOutputBuffers();
850 * Override the last modified timestamp
852 * @param string $timestamp New timestamp, in a format readable by
855 public function setLastModified( $timestamp ) {
856 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
860 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
862 * @param string $policy The literal string to output as the contents of
863 * the meta tag. Will be parsed according to the spec and output in
867 public function setRobotPolicy( $policy ) {
868 $policy = Article
::formatRobotPolicy( $policy );
870 if ( isset( $policy['index'] ) ) {
871 $this->setIndexPolicy( $policy['index'] );
873 if ( isset( $policy['follow'] ) ) {
874 $this->setFollowPolicy( $policy['follow'] );
879 * Set the index policy for the page, but leave the follow policy un-
882 * @param string $policy Either 'index' or 'noindex'.
885 public function setIndexPolicy( $policy ) {
886 $policy = trim( $policy );
887 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
888 $this->mIndexPolicy
= $policy;
893 * Set the follow policy for the page, but leave the index policy un-
896 * @param string $policy Either 'follow' or 'nofollow'.
899 public function setFollowPolicy( $policy ) {
900 $policy = trim( $policy );
901 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
902 $this->mFollowPolicy
= $policy;
907 * Set the new value of the "action text", this will be added to the
908 * "HTML title", separated from it with " - ".
910 * @param string $text New value of the "action text"
912 public function setPageTitleActionText( $text ) {
913 $this->mPageTitleActionText
= $text;
917 * Get the value of the "action text"
921 public function getPageTitleActionText() {
922 return $this->mPageTitleActionText
;
926 * "HTML title" means the contents of "<title>".
927 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
929 * @param string|Message $name
931 public function setHTMLTitle( $name ) {
932 if ( $name instanceof Message
) {
933 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
935 $this->mHTMLtitle
= $name;
940 * Return the "HTML title", i.e. the content of the "<title>" tag.
944 public function getHTMLTitle() {
945 return $this->mHTMLtitle
;
949 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
953 public function setRedirectedFrom( $t ) {
954 $this->mRedirectedFrom
= $t;
958 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
959 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
960 * but not bad tags like \<script\>. This function automatically sets
961 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
962 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
963 * good tags like \<i\> will be dropped entirely.
965 * @param string|Message $name
967 public function setPageTitle( $name ) {
968 if ( $name instanceof Message
) {
969 $name = $name->setContext( $this->getContext() )->text();
972 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
973 # but leave "<i>foobar</i>" alone
974 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
975 $this->mPagetitle
= $nameWithTags;
977 # change "<i>foo&bar</i>" to "foo&bar"
979 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
980 ->inContentLanguage()
985 * Return the "page title", i.e. the content of the \<h1\> tag.
989 public function getPageTitle() {
990 return $this->mPagetitle
;
994 * Set the Title object to use
998 public function setTitle( Title
$t ) {
999 $this->getContext()->setTitle( $t );
1003 * Replace the subtitle with $str
1005 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1007 public function setSubtitle( $str ) {
1008 $this->clearSubtitle();
1009 $this->addSubtitle( $str );
1013 * Add $str to the subtitle
1015 * @deprecated since 1.19; use addSubtitle() instead
1016 * @param string|Message $str String or Message to add to the subtitle
1018 public function appendSubtitle( $str ) {
1019 $this->addSubtitle( $str );
1023 * Add $str to the subtitle
1025 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1027 public function addSubtitle( $str ) {
1028 if ( $str instanceof Message
) {
1029 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1031 $this->mSubtitle
[] = $str;
1036 * Build message object for a subtitle containing a backlink to a page
1038 * @param Title $title Title to link to
1039 * @param array $query Array of additional parameters to include in the link
1043 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1044 if ( $title->isRedirect() ) {
1045 $query['redirect'] = 'no';
1047 return wfMessage( 'backlinksubtitle' )
1048 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1052 * Add a subtitle containing a backlink to a page
1054 * @param Title $title Title to link to
1055 * @param array $query Array of additional parameters to include in the link
1057 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1058 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1062 * Clear the subtitles
1064 public function clearSubtitle() {
1065 $this->mSubtitle
= array();
1073 public function getSubtitle() {
1074 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1078 * Set the page as printable, i.e. it'll be displayed with all
1079 * print styles included
1081 public function setPrintable() {
1082 $this->mPrintable
= true;
1086 * Return whether the page is "printable"
1090 public function isPrintable() {
1091 return $this->mPrintable
;
1095 * Disable output completely, i.e. calling output() will have no effect
1097 public function disable() {
1098 $this->mDoNothing
= true;
1102 * Return whether the output will be completely disabled
1106 public function isDisabled() {
1107 return $this->mDoNothing
;
1111 * Show an "add new section" link?
1115 public function showNewSectionLink() {
1116 return $this->mNewSectionLink
;
1120 * Forcibly hide the new section link?
1124 public function forceHideNewSectionLink() {
1125 return $this->mHideNewSectionLink
;
1129 * Add or remove feed links in the page header
1130 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1131 * for the new version
1132 * @see addFeedLink()
1134 * @param bool $show True: add default feeds, false: remove all feeds
1136 public function setSyndicated( $show = true ) {
1138 $this->setFeedAppendQuery( false );
1140 $this->mFeedLinks
= array();
1145 * Add default feeds to the page header
1146 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1147 * for the new version
1148 * @see addFeedLink()
1150 * @param string $val Query to append to feed links or false to output
1153 public function setFeedAppendQuery( $val ) {
1154 $this->mFeedLinks
= array();
1156 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1157 $query = "feed=$type";
1158 if ( is_string( $val ) ) {
1159 $query .= '&' . $val;
1161 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1166 * Add a feed link to the page header
1168 * @param string $format Feed type, should be a key of $wgFeedClasses
1169 * @param string $href URL
1171 public function addFeedLink( $format, $href ) {
1172 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1173 $this->mFeedLinks
[$format] = $href;
1178 * Should we output feed links for this page?
1181 public function isSyndicated() {
1182 return count( $this->mFeedLinks
) > 0;
1186 * Return URLs for each supported syndication format for this page.
1187 * @return array Associating format keys with URLs
1189 public function getSyndicationLinks() {
1190 return $this->mFeedLinks
;
1194 * Will currently always return null
1198 public function getFeedAppendQuery() {
1199 return $this->mFeedLinksAppendQuery
;
1203 * Set whether the displayed content is related to the source of the
1204 * corresponding article on the wiki
1205 * Setting true will cause the change "article related" toggle to true
1209 public function setArticleFlag( $v ) {
1210 $this->mIsarticle
= $v;
1212 $this->mIsArticleRelated
= $v;
1217 * Return whether the content displayed page is related to the source of
1218 * the corresponding article on the wiki
1222 public function isArticle() {
1223 return $this->mIsarticle
;
1227 * Set whether this page is related an article on the wiki
1228 * Setting false will cause the change of "article flag" toggle to false
1232 public function setArticleRelated( $v ) {
1233 $this->mIsArticleRelated
= $v;
1235 $this->mIsarticle
= false;
1240 * Return whether this page is related an article on the wiki
1244 public function isArticleRelated() {
1245 return $this->mIsArticleRelated
;
1249 * Add new language links
1251 * @param array $newLinkArray Associative array mapping language code to the page
1254 public function addLanguageLinks( array $newLinkArray ) {
1255 $this->mLanguageLinks +
= $newLinkArray;
1259 * Reset the language links and add new language links
1261 * @param array $newLinkArray Associative array mapping language code to the page
1264 public function setLanguageLinks( array $newLinkArray ) {
1265 $this->mLanguageLinks
= $newLinkArray;
1269 * Get the list of language links
1271 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1273 public function getLanguageLinks() {
1274 return $this->mLanguageLinks
;
1278 * Add an array of categories, with names in the keys
1280 * @param array $categories Mapping category name => sort key
1282 public function addCategoryLinks( array $categories ) {
1285 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1289 # Add the links to a LinkBatch
1290 $arr = array( NS_CATEGORY
=> $categories );
1291 $lb = new LinkBatch
;
1292 $lb->setArray( $arr );
1294 # Fetch existence plus the hiddencat property
1295 $dbr = wfGetDB( DB_SLAVE
);
1296 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1297 'page_is_redirect', 'page_latest', 'pp_value' );
1299 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1300 $fields[] = 'page_content_model';
1303 $res = $dbr->select( array( 'page', 'page_props' ),
1305 $lb->constructSet( 'page', $dbr ),
1308 array( 'page_props' => array( 'LEFT JOIN', array(
1309 'pp_propname' => 'hiddencat',
1314 # Add the results to the link cache
1315 $lb->addResultToCache( LinkCache
::singleton(), $res );
1317 # Set all the values to 'normal'.
1318 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1320 # Mark hidden categories
1321 foreach ( $res as $row ) {
1322 if ( isset( $row->pp_value
) ) {
1323 $categories[$row->page_title
] = 'hidden';
1327 # Add the remaining categories to the skin
1329 'OutputPageMakeCategoryLinks',
1330 array( &$this, $categories, &$this->mCategoryLinks
) )
1332 foreach ( $categories as $category => $type ) {
1333 $origcategory = $category;
1334 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1338 $wgContLang->findVariantLink( $category, $title, true );
1339 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1342 $text = $wgContLang->convertHtml( $title->getText() );
1343 $this->mCategories
[] = $title->getText();
1344 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1350 * Reset the category links (but not the category list) and add $categories
1352 * @param array $categories Mapping category name => sort key
1354 public function setCategoryLinks( array $categories ) {
1355 $this->mCategoryLinks
= array();
1356 $this->addCategoryLinks( $categories );
1360 * Get the list of category links, in a 2-D array with the following format:
1361 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1362 * hidden categories) and $link a HTML fragment with a link to the category
1367 public function getCategoryLinks() {
1368 return $this->mCategoryLinks
;
1372 * Get the list of category names this page belongs to
1374 * @return array Array of strings
1376 public function getCategories() {
1377 return $this->mCategories
;
1381 * Add an array of indicators, with their identifiers as array keys and HTML contents as values.
1383 * In case of duplicate keys, existing values are overwritten.
1385 * @param array $indicators
1388 public function setIndicators( array $indicators ) {
1389 $this->mIndicators
= $indicators +
$this->mIndicators
;
1390 // Keep ordered by key
1391 ksort( $this->mIndicators
);
1395 * Get the indicators associated with this page.
1397 * The array will be internally ordered by item keys.
1399 * @return array Keys: identifiers, values: HTML contents
1402 public function getIndicators() {
1403 return $this->mIndicators
;
1407 * Do not allow scripts which can be modified by wiki users to load on this page;
1408 * only allow scripts bundled with, or generated by, the software.
1409 * Site-wide styles are controlled by a config setting, since they can be
1410 * used to create a custom skin/theme, but not user-specific ones.
1412 * @todo this should be given a more accurate name
1414 public function disallowUserJs() {
1415 $this->reduceAllowedModules(
1416 ResourceLoaderModule
::TYPE_SCRIPTS
,
1417 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1420 // Site-wide styles are controlled by a config setting, see bug 71621
1421 // for background on why. User styles are never allowed.
1422 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1423 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1425 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1427 $this->reduceAllowedModules(
1428 ResourceLoaderModule
::TYPE_STYLES
,
1434 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1435 * @see ResourceLoaderModule::$origin
1436 * @param string $type ResourceLoaderModule TYPE_ constant
1437 * @return int ResourceLoaderModule ORIGIN_ class constant
1439 public function getAllowedModules( $type ) {
1440 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1441 return min( array_values( $this->mAllowedModules
) );
1443 return isset( $this->mAllowedModules
[$type] )
1444 ?
$this->mAllowedModules
[$type]
1445 : ResourceLoaderModule
::ORIGIN_ALL
;
1450 * Set the highest level of CSS/JS untrustworthiness allowed
1452 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1453 * Use reduceAllowedModules() instead
1454 * @param string $type ResourceLoaderModule TYPE_ constant
1455 * @param int $level ResourceLoaderModule class constant
1457 public function setAllowedModules( $type, $level ) {
1458 wfDeprecated( __METHOD__
, '1.24' );
1459 $this->reduceAllowedModules( $type, $level );
1463 * Limit the highest level of CSS/JS untrustworthiness allowed.
1465 * If passed the same or a higher level than the current level of untrustworthiness set, the
1466 * level will remain unchanged.
1468 * @param string $type
1469 * @param int $level ResourceLoaderModule class constant
1471 public function reduceAllowedModules( $type, $level ) {
1472 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1476 * Prepend $text to the body HTML
1478 * @param string $text HTML
1480 public function prependHTML( $text ) {
1481 $this->mBodytext
= $text . $this->mBodytext
;
1485 * Append $text to the body HTML
1487 * @param string $text HTML
1489 public function addHTML( $text ) {
1490 $this->mBodytext
.= $text;
1494 * Shortcut for adding an Html::element via addHTML.
1498 * @param string $element
1499 * @param array $attribs
1500 * @param string $contents
1502 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1503 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1507 * Clear the body HTML
1509 public function clearHTML() {
1510 $this->mBodytext
= '';
1516 * @return string HTML
1518 public function getHTML() {
1519 return $this->mBodytext
;
1523 * Get/set the ParserOptions object to use for wikitext parsing
1525 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1526 * current ParserOption object
1527 * @return ParserOptions
1529 public function parserOptions( $options = null ) {
1530 if ( !$this->mParserOptions
) {
1531 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1532 $this->mParserOptions
->setEditSection( false );
1534 return wfSetVar( $this->mParserOptions
, $options );
1538 * Set the revision ID which will be seen by the wiki text parser
1539 * for things such as embedded {{REVISIONID}} variable use.
1541 * @param int|null $revid An positive integer, or null
1542 * @return mixed Previous value
1544 public function setRevisionId( $revid ) {
1545 $val = is_null( $revid ) ?
null : intval( $revid );
1546 return wfSetVar( $this->mRevisionId
, $val );
1550 * Get the displayed revision ID
1554 public function getRevisionId() {
1555 return $this->mRevisionId
;
1559 * Set the timestamp of the revision which will be displayed. This is used
1560 * to avoid a extra DB call in Skin::lastModified().
1562 * @param string|null $timestamp
1563 * @return mixed Previous value
1565 public function setRevisionTimestamp( $timestamp ) {
1566 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1570 * Get the timestamp of displayed revision.
1571 * This will be null if not filled by setRevisionTimestamp().
1573 * @return string|null
1575 public function getRevisionTimestamp() {
1576 return $this->mRevisionTimestamp
;
1580 * Set the displayed file version
1582 * @param File|bool $file
1583 * @return mixed Previous value
1585 public function setFileVersion( $file ) {
1587 if ( $file instanceof File
&& $file->exists() ) {
1588 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1590 return wfSetVar( $this->mFileVersion
, $val, true );
1594 * Get the displayed file version
1596 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1598 public function getFileVersion() {
1599 return $this->mFileVersion
;
1603 * Get the templates used on this page
1605 * @return array (namespace => dbKey => revId)
1608 public function getTemplateIds() {
1609 return $this->mTemplateIds
;
1613 * Get the files used on this page
1615 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1618 public function getFileSearchOptions() {
1619 return $this->mImageTimeKeys
;
1623 * Convert wikitext to HTML and add it to the buffer
1624 * Default assumes that the current page title will be used.
1626 * @param string $text
1627 * @param bool $linestart Is this the start of a line?
1628 * @param bool $interface Is this text in the user interface language?
1629 * @throws MWException
1631 public function addWikiText( $text, $linestart = true, $interface = true ) {
1632 $title = $this->getTitle(); // Work around E_STRICT
1634 throw new MWException( 'Title is null' );
1636 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1640 * Add wikitext with a custom Title object
1642 * @param string $text Wikitext
1643 * @param Title $title
1644 * @param bool $linestart Is this the start of a line?
1646 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1647 $this->addWikiTextTitle( $text, $title, $linestart );
1651 * Add wikitext with a custom Title object and tidy enabled.
1653 * @param string $text Wikitext
1654 * @param Title $title
1655 * @param bool $linestart Is this the start of a line?
1657 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1658 $this->addWikiTextTitle( $text, $title, $linestart, true );
1662 * Add wikitext with tidy enabled
1664 * @param string $text Wikitext
1665 * @param bool $linestart Is this the start of a line?
1667 public function addWikiTextTidy( $text, $linestart = true ) {
1668 $title = $this->getTitle();
1669 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1673 * Add wikitext with a custom Title object
1675 * @param string $text Wikitext
1676 * @param Title $title
1677 * @param bool $linestart Is this the start of a line?
1678 * @param bool $tidy Whether to use tidy
1679 * @param bool $interface Whether it is an interface message
1680 * (for example disables conversion)
1682 public function addWikiTextTitle( $text, Title
$title, $linestart,
1683 $tidy = false, $interface = false
1687 wfProfileIn( __METHOD__
);
1689 $popts = $this->parserOptions();
1690 $oldTidy = $popts->setTidy( $tidy );
1691 $popts->setInterfaceMessage( (bool)$interface );
1693 $parserOutput = $wgParser->getFreshParser()->parse(
1694 $text, $title, $popts,
1695 $linestart, true, $this->mRevisionId
1698 $popts->setTidy( $oldTidy );
1700 $this->addParserOutput( $parserOutput );
1702 wfProfileOut( __METHOD__
);
1706 * Add a ParserOutput object, but without Html.
1708 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1709 * @param ParserOutput $parserOutput
1711 public function addParserOutputNoText( $parserOutput ) {
1712 $this->addParserOutputMetadata( $parserOutput );
1716 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1717 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1721 * @param ParserOutput $parserOutput
1723 public function addParserOutputMetadata( $parserOutput ) {
1724 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1725 $this->addCategoryLinks( $parserOutput->getCategories() );
1726 $this->setIndicators( $parserOutput->getIndicators() );
1727 $this->mNewSectionLink
= $parserOutput->getNewSection();
1728 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1730 $this->mParseWarnings
= $parserOutput->getWarnings();
1731 if ( !$parserOutput->isCacheable() ) {
1732 $this->enableClientCache( false );
1734 $this->mNoGallery
= $parserOutput->getNoGallery();
1735 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1736 $this->addModules( $parserOutput->getModules() );
1737 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1738 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1739 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1740 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1741 $this->mPreventClickjacking
= $this->mPreventClickjacking
1742 ||
$parserOutput->preventClickjacking();
1744 // Template versioning...
1745 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1746 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1747 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1749 $this->mTemplateIds
[$ns] = $dbks;
1752 // File versioning...
1753 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1754 $this->mImageTimeKeys
[$dbk] = $data;
1757 // Hooks registered in the object
1758 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1759 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1760 list( $hookName, $data ) = $hookInfo;
1761 if ( isset( $parserOutputHooks[$hookName] ) ) {
1762 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1766 // Link flags are ignored for now, but may in the future be
1767 // used to mark individual language links.
1768 $linkFlags = array();
1769 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1770 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1774 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1775 * ParserOutput object, without any other metadata.
1778 * @param ParserOutput $parserOutput
1780 public function addParserOutputContent( $parserOutput ) {
1781 $this->addParserOutputText( $parserOutput );
1783 $this->addModules( $parserOutput->getModules() );
1784 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1785 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1786 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1788 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1792 * Add the HTML associated with a ParserOutput object, without any metadata.
1795 * @param ParserOutput $parserOutput
1797 public function addParserOutputText( $parserOutput ) {
1798 $text = $parserOutput->getText();
1799 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1800 $this->addHTML( $text );
1804 * Add everything from a ParserOutput object.
1806 * @param ParserOutput $parserOutput
1808 function addParserOutput( $parserOutput ) {
1809 $this->addParserOutputMetadata( $parserOutput );
1810 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1812 // Touch section edit links only if not previously disabled
1813 if ( $parserOutput->getEditSectionTokens() ) {
1814 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1817 $this->addParserOutputText( $parserOutput );
1821 * Add the output of a QuickTemplate to the output buffer
1823 * @param QuickTemplate $template
1825 public function addTemplate( &$template ) {
1826 $this->addHTML( $template->getHTML() );
1830 * Parse wikitext and return the HTML.
1832 * @param string $text
1833 * @param bool $linestart Is this the start of a line?
1834 * @param bool $interface Use interface language ($wgLang instead of
1835 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1836 * This also disables LanguageConverter.
1837 * @param Language $language Target language object, will override $interface
1838 * @throws MWException
1839 * @return string HTML
1841 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1844 if ( is_null( $this->getTitle() ) ) {
1845 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1848 $popts = $this->parserOptions();
1850 $popts->setInterfaceMessage( true );
1852 if ( $language !== null ) {
1853 $oldLang = $popts->setTargetLanguage( $language );
1856 $parserOutput = $wgParser->getFreshParser()->parse(
1857 $text, $this->getTitle(), $popts,
1858 $linestart, true, $this->mRevisionId
1862 $popts->setInterfaceMessage( false );
1864 if ( $language !== null ) {
1865 $popts->setTargetLanguage( $oldLang );
1868 return $parserOutput->getText();
1872 * Parse wikitext, strip paragraphs, 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
1878 * words like GRAMMAR and PLURAL
1879 * @return string HTML
1881 public function parseInline( $text, $linestart = true, $interface = false ) {
1882 $parsed = $this->parse( $text, $linestart, $interface );
1883 return Parser
::stripOuterParagraph( $parsed );
1887 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1889 * @param int $maxage Maximum cache time on the Squid, in seconds.
1891 public function setSquidMaxage( $maxage ) {
1892 $this->mSquidMaxage
= $maxage;
1896 * Use enableClientCache(false) to force it to send nocache headers
1898 * @param bool $state
1902 public function enableClientCache( $state ) {
1903 return wfSetVar( $this->mEnableClientCache
, $state );
1907 * Get the list of cookies that will influence on the cache
1911 function getCacheVaryCookies() {
1913 if ( $cookies === null ) {
1914 $config = $this->getConfig();
1915 $cookies = array_merge(
1917 $config->get( 'CookiePrefix' ) . 'Token',
1918 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1922 $config->get( 'CacheVaryCookies' )
1924 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1930 * Check if the request has a cache-varying cookie header
1931 * If it does, it's very important that we don't allow public caching
1935 function haveCacheVaryCookies() {
1936 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1937 if ( $cookieHeader === false ) {
1940 $cvCookies = $this->getCacheVaryCookies();
1941 foreach ( $cvCookies as $cookieName ) {
1942 # Check for a simple string match, like the way squid does it
1943 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1944 wfDebug( __METHOD__
. ": found $cookieName\n" );
1948 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1953 * Add an HTTP header that will influence on the cache
1955 * @param string $header Header name
1956 * @param array|null $option
1957 * @todo FIXME: Document the $option parameter; it appears to be for
1958 * X-Vary-Options but what format is acceptable?
1960 public function addVaryHeader( $header, $option = null ) {
1961 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1962 $this->mVaryHeader
[$header] = (array)$option;
1963 } elseif ( is_array( $option ) ) {
1964 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1965 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1967 $this->mVaryHeader
[$header] = $option;
1970 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1974 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1975 * such as Accept-Encoding or Cookie
1979 public function getVaryHeader() {
1980 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1984 * Get a complete X-Vary-Options header
1988 public function getXVO() {
1989 $cvCookies = $this->getCacheVaryCookies();
1991 $cookiesOption = array();
1992 foreach ( $cvCookies as $cookieName ) {
1993 $cookiesOption[] = 'string-contains=' . $cookieName;
1995 $this->addVaryHeader( 'Cookie', $cookiesOption );
1998 foreach ( $this->mVaryHeader
as $header => $option ) {
1999 $newheader = $header;
2000 if ( is_array( $option ) && count( $option ) > 0 ) {
2001 $newheader .= ';' . implode( ';', $option );
2003 $headers[] = $newheader;
2005 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2011 * bug 21672: Add Accept-Language to Vary and XVO headers
2012 * if there's no 'variant' parameter existed in GET.
2015 * /w/index.php?title=Main_page should always be served; but
2016 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2018 function addAcceptLanguage() {
2019 $title = $this->getTitle();
2020 if ( !$title instanceof Title
) {
2024 $lang = $title->getPageLanguage();
2025 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2026 $variants = $lang->getVariants();
2027 $aloption = array();
2028 foreach ( $variants as $variant ) {
2029 if ( $variant === $lang->getCode() ) {
2032 $aloption[] = 'string-contains=' . $variant;
2034 // IE and some other browsers use BCP 47 standards in
2035 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2036 // We should handle these too.
2037 $variantBCP47 = wfBCP47( $variant );
2038 if ( $variantBCP47 !== $variant ) {
2039 $aloption[] = 'string-contains=' . $variantBCP47;
2043 $this->addVaryHeader( 'Accept-Language', $aloption );
2048 * Set a flag which will cause an X-Frame-Options header appropriate for
2049 * edit pages to be sent. The header value is controlled by
2050 * $wgEditPageFrameOptions.
2052 * This is the default for special pages. If you display a CSRF-protected
2053 * form on an ordinary view page, then you need to call this function.
2055 * @param bool $enable
2057 public function preventClickjacking( $enable = true ) {
2058 $this->mPreventClickjacking
= $enable;
2062 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2063 * This can be called from pages which do not contain any CSRF-protected
2066 public function allowClickjacking() {
2067 $this->mPreventClickjacking
= false;
2071 * Get the prevent-clickjacking flag
2076 public function getPreventClickjacking() {
2077 return $this->mPreventClickjacking
;
2081 * Get the X-Frame-Options header value (without the name part), or false
2082 * if there isn't one. This is used by Skin to determine whether to enable
2083 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2087 public function getFrameOptions() {
2088 $config = $this->getConfig();
2089 if ( $config->get( 'BreakFrames' ) ) {
2091 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2092 return $config->get( 'EditPageFrameOptions' );
2098 * Send cache control HTTP headers
2100 public function sendCacheControl() {
2101 $response = $this->getRequest()->response();
2102 $config = $this->getConfig();
2103 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2104 $response->header( "ETag: $this->mETag" );
2107 $this->addVaryHeader( 'Cookie' );
2108 $this->addAcceptLanguage();
2110 # don't serve compressed data to clients who can't handle it
2111 # maintain different caches for logged-in users and non-logged in ones
2112 $response->header( $this->getVaryHeader() );
2114 if ( $config->get( 'UseXVO' ) ) {
2115 # Add an X-Vary-Options header for Squid with Wikimedia patches
2116 $response->header( $this->getXVO() );
2119 if ( $this->mEnableClientCache
) {
2121 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2122 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2124 if ( $config->get( 'UseESI' ) ) {
2125 # We'll purge the proxy cache explicitly, but require end user agents
2126 # to revalidate against the proxy on each visit.
2127 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2128 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2129 # start with a shorter timeout for initial testing
2130 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2131 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2132 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2133 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2135 # We'll purge the proxy cache for anons explicitly, but require end user agents
2136 # to revalidate against the proxy on each visit.
2137 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2138 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2139 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2140 # start with a shorter timeout for initial testing
2141 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2142 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2143 . ', must-revalidate, max-age=0' );
2146 # We do want clients to cache if they can, but they *must* check for updates
2147 # on revisiting the page.
2148 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2149 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2150 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2152 if ( $this->mLastModified
) {
2153 $response->header( "Last-Modified: {$this->mLastModified}" );
2156 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2158 # In general, the absence of a last modified header should be enough to prevent
2159 # the client from using its cache. We send a few other things just to make sure.
2160 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2161 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2162 $response->header( 'Pragma: no-cache' );
2167 * Finally, all the text has been munged and accumulated into
2168 * the object, let's actually output it:
2170 public function output() {
2171 if ( $this->mDoNothing
) {
2175 wfProfileIn( __METHOD__
);
2177 $response = $this->getRequest()->response();
2178 $config = $this->getConfig();
2180 if ( $this->mRedirect
!= '' ) {
2181 # Standards require redirect URLs to be absolute
2182 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2184 $redirect = $this->mRedirect
;
2185 $code = $this->mRedirectCode
;
2187 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2188 if ( $code == '301' ||
$code == '303' ) {
2189 if ( !$config->get( 'DebugRedirects' ) ) {
2190 $message = HttpStatus
::getMessage( $code );
2191 $response->header( "HTTP/1.1 $code $message" );
2193 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2195 if ( $config->get( 'VaryOnXFP' ) ) {
2196 $this->addVaryHeader( 'X-Forwarded-Proto' );
2198 $this->sendCacheControl();
2200 $response->header( "Content-Type: text/html; charset=utf-8" );
2201 if ( $config->get( 'DebugRedirects' ) ) {
2202 $url = htmlspecialchars( $redirect );
2203 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2204 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2205 print "</body>\n</html>\n";
2207 $response->header( 'Location: ' . $redirect );
2211 wfProfileOut( __METHOD__
);
2213 } elseif ( $this->mStatusCode
) {
2214 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2216 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2220 # Buffer output; final headers may depend on later processing
2223 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2224 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2226 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2227 // jQuery etc. can work correctly.
2228 $response->header( 'X-UA-Compatible: IE=Edge' );
2230 // Prevent framing, if requested
2231 $frameOptions = $this->getFrameOptions();
2232 if ( $frameOptions ) {
2233 $response->header( "X-Frame-Options: $frameOptions" );
2236 if ( $this->mArticleBodyOnly
) {
2237 echo $this->mBodytext
;
2240 $sk = $this->getSkin();
2241 // add skin specific modules
2242 $modules = $sk->getDefaultModules();
2244 // enforce various default modules for all skins
2245 $coreModules = array(
2246 // keep this list as small as possible
2247 'mediawiki.page.startup',
2251 // Support for high-density display images if enabled
2252 if ( $config->get( 'ResponsiveImages' ) ) {
2253 $coreModules[] = 'mediawiki.hidpi';
2256 $this->addModules( $coreModules );
2257 foreach ( $modules as $group ) {
2258 $this->addModules( $group );
2260 MWDebug
::addModules( $this );
2262 // Hook that allows last minute changes to the output page, e.g.
2263 // adding of CSS or Javascript by extensions.
2264 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2266 wfProfileIn( 'Output-skin' );
2268 wfProfileOut( 'Output-skin' );
2271 // This hook allows last minute changes to final overall output by modifying output buffer
2272 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2274 $this->sendCacheControl();
2278 wfProfileOut( __METHOD__
);
2282 * Actually output something with print.
2284 * @param string $ins The string to output
2285 * @deprecated since 1.22 Use echo yourself.
2287 public function out( $ins ) {
2288 wfDeprecated( __METHOD__
, '1.22' );
2293 * Produce a "user is blocked" page.
2294 * @deprecated since 1.18
2296 function blockedPage() {
2297 throw new UserBlockedError( $this->getUser()->mBlock
);
2301 * Prepare this object to display an error page; disable caching and
2302 * indexing, clear the current text and redirect, set the page's title
2303 * and optionally an custom HTML title (content of the "<title>" tag).
2305 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2306 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2307 * optional, if not passed the "<title>" attribute will be
2308 * based on $pageTitle
2310 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2311 $this->setPageTitle( $pageTitle );
2312 if ( $htmlTitle !== false ) {
2313 $this->setHTMLTitle( $htmlTitle );
2315 $this->setRobotPolicy( 'noindex,nofollow' );
2316 $this->setArticleRelated( false );
2317 $this->enableClientCache( false );
2318 $this->mRedirect
= '';
2319 $this->clearSubtitle();
2324 * Output a standard error page
2326 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2327 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2328 * showErrorPage( 'titlemsg', $messageObject );
2329 * showErrorPage( $titleMessageObject, $messageObject );
2331 * @param string|Message $title Message key (string) for page title, or a Message object
2332 * @param string|Message $msg Message key (string) for page text, or a Message object
2333 * @param array $params Message parameters; ignored if $msg is a Message object
2335 public function showErrorPage( $title, $msg, $params = array() ) {
2336 if ( !$title instanceof Message
) {
2337 $title = $this->msg( $title );
2340 $this->prepareErrorPage( $title );
2342 if ( $msg instanceof Message
) {
2343 if ( $params !== array() ) {
2344 trigger_error( 'Argument ignored: $params. The message parameters argument '
2345 . 'is discarded when the $msg argument is a Message object instead of '
2346 . 'a string.', E_USER_NOTICE
);
2348 $this->addHTML( $msg->parseAsBlock() );
2350 $this->addWikiMsgArray( $msg, $params );
2353 $this->returnToMain();
2357 * Output a standard permission error page
2359 * @param array $errors Error message keys
2360 * @param string $action Action that was denied or null if unknown
2362 public function showPermissionsErrorPage( array $errors, $action = null ) {
2363 // For some action (read, edit, create and upload), display a "login to do this action"
2364 // error if all of the following conditions are met:
2365 // 1. the user is not logged in
2366 // 2. the only error is insufficient permissions (i.e. no block or something else)
2367 // 3. the error can be avoided simply by logging in
2368 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2369 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2370 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2371 && ( User
::groupHasPermission( 'user', $action )
2372 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2374 $displayReturnto = null;
2376 # Due to bug 32276, if a user does not have read permissions,
2377 # $this->getTitle() will just give Special:Badtitle, which is
2378 # not especially useful as a returnto parameter. Use the title
2379 # from the request instead, if there was one.
2380 $request = $this->getRequest();
2381 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2382 if ( $action == 'edit' ) {
2383 $msg = 'whitelistedittext';
2384 $displayReturnto = $returnto;
2385 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2386 $msg = 'nocreatetext';
2387 } elseif ( $action == 'upload' ) {
2388 $msg = 'uploadnologintext';
2390 $msg = 'loginreqpagetext';
2391 $displayReturnto = Title
::newMainPage();
2397 $query['returnto'] = $returnto->getPrefixedText();
2399 if ( !$request->wasPosted() ) {
2400 $returntoquery = $request->getValues();
2401 unset( $returntoquery['title'] );
2402 unset( $returntoquery['returnto'] );
2403 unset( $returntoquery['returntoquery'] );
2404 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2407 $loginLink = Linker
::linkKnown(
2408 SpecialPage
::getTitleFor( 'Userlogin' ),
2409 $this->msg( 'loginreqlink' )->escaped(),
2414 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2415 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2417 # Don't return to a page the user can't read otherwise
2418 # we'll end up in a pointless loop
2419 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2420 $this->returnToMain( null, $displayReturnto );
2423 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2424 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2429 * Display an error page indicating that a given version of MediaWiki is
2430 * required to use it
2432 * @param mixed $version The version of MediaWiki needed to use the page
2434 public function versionRequired( $version ) {
2435 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2437 $this->addWikiMsg( 'versionrequiredtext', $version );
2438 $this->returnToMain();
2442 * Display an error page noting that a given permission bit is required.
2443 * @deprecated since 1.18, just throw the exception directly
2444 * @param string $permission Key required
2445 * @throws PermissionsError
2447 public function permissionRequired( $permission ) {
2448 throw new PermissionsError( $permission );
2452 * Produce the stock "please login to use the wiki" page
2454 * @deprecated since 1.19; throw the exception directly
2456 public function loginToUse() {
2457 throw new PermissionsError( 'read' );
2461 * Format a list of error messages
2463 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2464 * @param string $action Action that was denied or null if unknown
2465 * @return string The wikitext error-messages, formatted into a list.
2467 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2468 if ( $action == null ) {
2469 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2471 $action_desc = $this->msg( "action-$action" )->plain();
2473 'permissionserrorstext-withaction',
2476 )->plain() . "\n\n";
2479 if ( count( $errors ) > 1 ) {
2480 $text .= '<ul class="permissions-errors">' . "\n";
2482 foreach ( $errors as $error ) {
2484 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2489 $text .= "<div class=\"permissions-errors\">\n" .
2490 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2498 * Display a page stating that the Wiki is in read-only mode.
2499 * Should only be called after wfReadOnly() has returned true.
2501 * Historically, this function was used to show the source of the page that the user
2502 * was trying to edit and _also_ permissions error messages. The relevant code was
2503 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2505 * @deprecated since 1.25; throw the exception directly
2506 * @throws ReadOnlyError
2508 public function readOnlyPage() {
2509 if ( func_num_args() > 0 ) {
2510 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2513 throw new ReadOnlyError
;
2517 * Turn off regular page output and return an error response
2518 * for when rate limiting has triggered.
2520 * @deprecated since 1.25; throw the exception directly
2522 public function rateLimited() {
2523 wfDeprecated( __METHOD__
, '1.25' );
2524 throw new ThrottledError
;
2528 * Show a warning about slave lag
2530 * If the lag is higher than $wgSlaveLagCritical seconds,
2531 * then the warning is a bit more obvious. If the lag is
2532 * lower than $wgSlaveLagWarning, then no warning is shown.
2534 * @param int $lag Slave lag
2536 public function showLagWarning( $lag ) {
2537 $config = $this->getConfig();
2538 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2539 $message = $lag < $config->get( 'SlaveLagCritical' )
2542 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2543 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2547 public function showFatalError( $message ) {
2548 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2550 $this->addHTML( $message );
2553 public function showUnexpectedValueError( $name, $val ) {
2554 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2557 public function showFileCopyError( $old, $new ) {
2558 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2561 public function showFileRenameError( $old, $new ) {
2562 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2565 public function showFileDeleteError( $name ) {
2566 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2569 public function showFileNotFoundError( $name ) {
2570 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2574 * Add a "return to" link pointing to a specified title
2576 * @param Title $title Title to link
2577 * @param array $query Query string parameters
2578 * @param string $text Text of the link (input is not escaped)
2579 * @param array $options Options array to pass to Linker
2581 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2582 $link = $this->msg( 'returnto' )->rawParams(
2583 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2584 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2588 * Add a "return to" link pointing to a specified title,
2589 * or the title indicated in the request, or else the main page
2591 * @param mixed $unused
2592 * @param Title|string $returnto Title or String to return to
2593 * @param string $returntoquery Query string for the return to link
2595 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2596 if ( $returnto == null ) {
2597 $returnto = $this->getRequest()->getText( 'returnto' );
2600 if ( $returntoquery == null ) {
2601 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2604 if ( $returnto === '' ) {
2605 $returnto = Title
::newMainPage();
2608 if ( is_object( $returnto ) ) {
2609 $titleObj = $returnto;
2611 $titleObj = Title
::newFromText( $returnto );
2613 if ( !is_object( $titleObj ) ) {
2614 $titleObj = Title
::newMainPage();
2617 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2621 * @param Skin $sk The given Skin
2622 * @param bool $includeStyle Unused
2623 * @return string The doctype, opening "<html>", and head element.
2625 public function headElement( Skin
$sk, $includeStyle = true ) {
2628 $section = new ProfileSection( __METHOD__
);
2630 $userdir = $this->getLanguage()->getDir();
2631 $sitedir = $wgContLang->getDir();
2633 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2635 if ( $this->getHTMLTitle() == '' ) {
2636 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2639 $openHead = Html
::openElement( 'head' );
2641 # Don't bother with the newline if $head == ''
2642 $ret .= "$openHead\n";
2645 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2646 // Add <meta charset="UTF-8">
2647 // This should be before <title> since it defines the charset used by
2648 // text including the text inside <title>.
2649 // The spec recommends defining XHTML5's charset using the XML declaration
2651 // Our XML declaration is output by Html::htmlHeader.
2652 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2653 // http://www.whatwg.org/html/semantics.html#charset
2654 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2657 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2659 foreach ( $this->getHeadLinksArray() as $item ) {
2660 $ret .= $item . "\n";
2663 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2664 $ret .= $this->buildCssLinks();
2666 $ret .= $this->getHeadScripts() . "\n";
2668 foreach ( $this->mHeadItems
as $item ) {
2669 $ret .= $item . "\n";
2672 $closeHead = Html
::closeElement( 'head' );
2674 $ret .= "$closeHead\n";
2677 $bodyClasses = array();
2678 $bodyClasses[] = 'mediawiki';
2680 # Classes for LTR/RTL directionality support
2681 $bodyClasses[] = $userdir;
2682 $bodyClasses[] = "sitedir-$sitedir";
2684 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2685 # A <body> class is probably not the best way to do this . . .
2686 $bodyClasses[] = 'capitalize-all-nouns';
2689 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2690 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2692 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2694 $bodyAttrs = array();
2695 // While the implode() is not strictly needed, it's used for backwards compatibility
2696 // (this used to be built as a string and hooks likely still expect that).
2697 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2699 // Allow skins and extensions to add body attributes they need
2700 $sk->addToBodyAttributes( $this, $bodyAttrs );
2701 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2703 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2709 * Get a ResourceLoader object associated with this OutputPage
2711 * @return ResourceLoader
2713 public function getResourceLoader() {
2714 if ( is_null( $this->mResourceLoader
) ) {
2715 $this->mResourceLoader
= new ResourceLoader( $this->getConfig() );
2717 return $this->mResourceLoader
;
2722 * @param array|string $modules One or more module names
2723 * @param string $only ResourceLoaderModule TYPE_ class constant
2724 * @param bool $useESI
2725 * @param array $extraQuery Array with extra query parameters to add to each
2726 * request. array( param => value ).
2727 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2728 * call rather than a "<script src='...'>" tag.
2729 * @return string The html "<script>", "<link>" and "<style>" tags
2731 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2732 array $extraQuery = array(), $loadCall = false
2734 $modules = (array)$modules;
2738 'states' => array(),
2741 if ( !count( $modules ) ) {
2745 if ( count( $modules ) > 1 ) {
2746 // Remove duplicate module requests
2747 $modules = array_unique( $modules );
2748 // Sort module names so requests are more uniform
2751 if ( ResourceLoader
::inDebugMode() ) {
2752 // Recursively call us for every item
2753 foreach ( $modules as $name ) {
2754 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2755 $links['html'] .= $link['html'];
2756 $links['states'] +
= $link['states'];
2762 if ( !is_null( $this->mTarget
) ) {
2763 $extraQuery['target'] = $this->mTarget
;
2766 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2767 $sortedModules = array();
2768 $resourceLoader = $this->getResourceLoader();
2769 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2770 foreach ( $modules as $name ) {
2771 $module = $resourceLoader->getModule( $name );
2772 # Check that we're allowed to include this module on this page
2774 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2775 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2776 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2777 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2778 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2779 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2780 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2785 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2788 foreach ( $sortedModules as $source => $groups ) {
2789 foreach ( $groups as $group => $grpModules ) {
2790 // Special handling for user-specific groups
2792 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2793 $user = $this->getUser()->getName();
2796 // Create a fake request based on the one we are about to make so modules return
2797 // correct timestamp and emptiness data
2798 $query = ResourceLoader
::makeLoaderQuery(
2799 array(), // modules; not determined yet
2800 $this->getLanguage()->getCode(),
2801 $this->getSkin()->getSkinName(),
2803 null, // version; not determined yet
2804 ResourceLoader
::inDebugMode(),
2805 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2806 $this->isPrintable(),
2807 $this->getRequest()->getBool( 'handheld' ),
2810 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2812 // Extract modules that know they're empty and see if we have one or more
2815 foreach ( $grpModules as $key => $module ) {
2816 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2817 // If we're only getting the styles, we don't need to do anything for empty modules.
2818 if ( $module->isKnownEmpty( $context ) ) {
2819 unset( $grpModules[$key] );
2820 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2821 $links['states'][$key] = 'ready';
2825 $isRaw |
= $module->isRaw();
2828 // If there are no non-empty modules, skip this group
2829 if ( count( $grpModules ) === 0 ) {
2833 // Inline private modules. These can't be loaded through load.php for security
2834 // reasons, see bug 34907. Note that these modules should be loaded from
2835 // getHeadScripts() before the first loader call. Otherwise other modules can't
2836 // properly use them as dependencies (bug 30914)
2837 if ( $group === 'private' ) {
2838 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2839 $links['html'] .= Html
::inlineStyle(
2840 $resourceLoader->makeModuleResponse( $context, $grpModules )
2843 $links['html'] .= Html
::inlineScript(
2844 ResourceLoader
::makeLoaderConditionalScript(
2845 $resourceLoader->makeModuleResponse( $context, $grpModules )
2849 $links['html'] .= "\n";
2853 // Special handling for the user group; because users might change their stuff
2854 // on-wiki like user pages, or user preferences; we need to find the highest
2855 // timestamp of these user-changeable modules so we can ensure cache misses on change
2856 // This should NOT be done for the site group (bug 27564) because anons get that too
2857 // and we shouldn't be putting timestamps in Squid-cached HTML
2859 if ( $group === 'user' ) {
2860 // Get the maximum timestamp
2862 foreach ( $grpModules as $module ) {
2863 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2865 // Add a version parameter so cache will break when things change
2866 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2869 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2870 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2871 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2873 if ( $useESI && $resourceLoaderUseESI ) {
2874 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2875 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2876 $link = Html
::inlineStyle( $esi );
2878 $link = Html
::inlineScript( $esi );
2881 // Automatically select style/script elements
2882 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2883 $link = Html
::linkedStyle( $url );
2884 } elseif ( $loadCall ) {
2885 $link = Html
::inlineScript(
2886 ResourceLoader
::makeLoaderConditionalScript(
2887 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2891 $link = Html
::linkedScript( $url );
2892 if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
2893 // Wrap only=script requests in a conditional as browsers not supported
2894 // by the startup module would unconditionally execute this module.
2895 // Otherwise users will get "ReferenceError: mw is undefined" or
2896 // "jQuery is undefined" from e.g. a "site" module.
2897 $link = Html
::inlineScript(
2898 ResourceLoader
::makeLoaderConditionalScript(
2899 Xml
::encodeJsCall( 'document.write', array( $link ) )
2904 // For modules requested directly in the html via <link> or <script>,
2905 // tell mw.loader they are being loading to prevent duplicate requests.
2906 foreach ( $grpModules as $key => $module ) {
2907 // Don't output state=loading for the startup module..
2908 if ( $key !== 'startup' ) {
2909 $links['states'][$key] = 'loading';
2915 if ( $group == 'noscript' ) {
2916 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2918 $links['html'] .= $link . "\n";
2927 * Build html output from an array of links from makeResourceLoaderLink.
2928 * @param array $links
2929 * @return string HTML
2931 protected static function getHtmlFromLoaderLinks( array $links ) {
2934 foreach ( $links as $link ) {
2935 if ( !is_array( $link ) ) {
2938 $html .= $link['html'];
2939 $states +
= $link['states'];
2943 if ( count( $states ) ) {
2944 $html = Html
::inlineScript(
2945 ResourceLoader
::makeLoaderConditionalScript(
2946 ResourceLoader
::makeLoaderStateScript( $states )
2955 * JS stuff to put in the "<head>". This is the startup module, config
2956 * vars and modules marked with position 'top'
2958 * @return string HTML fragment
2960 function getHeadScripts() {
2961 // Startup - this will immediately load jquery and mediawiki modules
2963 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2965 // Load config before anything else
2966 $links[] = Html
::inlineScript(
2967 ResourceLoader
::makeLoaderConditionalScript(
2968 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2972 // Load embeddable private modules before any loader links
2973 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2974 // in mw.loader.implement() calls and deferred until mw.user is available
2975 $embedScripts = array( 'user.options', 'user.tokens' );
2976 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2978 // Scripts and messages "only" requests marked for top inclusion
2979 // Messages should go first
2980 $links[] = $this->makeResourceLoaderLink(
2981 $this->getModuleMessages( true, 'top' ),
2982 ResourceLoaderModule
::TYPE_MESSAGES
2984 $links[] = $this->makeResourceLoaderLink(
2985 $this->getModuleScripts( true, 'top' ),
2986 ResourceLoaderModule
::TYPE_SCRIPTS
2989 // Modules requests - let the client calculate dependencies and batch requests as it likes
2990 // Only load modules that have marked themselves for loading at the top
2991 $modules = $this->getModules( true, 'top' );
2993 $links[] = Html
::inlineScript(
2994 ResourceLoader
::makeLoaderConditionalScript(
2995 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3000 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3001 $links[] = $this->getScriptsForBottomQueue( true );
3004 return self
::getHtmlFromLoaderLinks( $links );
3008 * JS stuff to put at the 'bottom', which can either be the bottom of the
3009 * "<body>" or the bottom of the "<head>" depending on
3010 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3011 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3014 * @param bool $inHead If true, this HTML goes into the "<head>",
3015 * if false it goes into the "<body>".
3018 function getScriptsForBottomQueue( $inHead ) {
3019 // Scripts and messages "only" requests marked for bottom inclusion
3020 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3021 // Messages should go first
3023 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
3024 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
3025 /* $loadCall = */ $inHead
3027 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3028 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
3029 /* $loadCall = */ $inHead
3032 // Modules requests - let the client calculate dependencies and batch requests as it likes
3033 // Only load modules that have marked themselves for loading at the bottom
3034 $modules = $this->getModules( true, 'bottom' );
3036 $links[] = Html
::inlineScript(
3037 ResourceLoader
::makeLoaderConditionalScript(
3038 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3044 $links[] = "\n" . $this->mScripts
;
3046 // Add site JS if enabled
3047 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
3048 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3051 // Add user JS if enabled
3052 if ( $this->getConfig()->get( 'AllowUserJs' )
3053 && $this->getUser()->isLoggedIn()
3054 && $this->getTitle()
3055 && $this->getTitle()->isJsSubpage()
3056 && $this->userCanPreview()
3058 # XXX: additional security check/prompt?
3059 // We're on a preview of a JS subpage
3060 // Exclude this page from the user module in case it's in there (bug 26283)
3061 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3062 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3064 // Load the previewed JS
3065 $links[] = Html
::inlineScript( "\n"
3066 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3068 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3069 // asynchronously and may arrive *after* the inline script here. So the previewed code
3070 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3072 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3073 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3074 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3078 // Group JS is only enabled if site JS is enabled.
3079 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3080 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3083 return self
::getHtmlFromLoaderLinks( $links );
3087 * JS stuff to put at the bottom of the "<body>"
3090 function getBottomScripts() {
3091 // Optimise jQuery ready event cross-browser.
3092 // This also enforces $.isReady to be true at </body> which fixes the
3093 // mw.loader bug in Firefox with using document.write between </body>
3094 // and the DOMContentReady event (bug 47457).
3095 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3097 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3098 $html .= $this->getScriptsForBottomQueue( false );
3105 * Get the javascript config vars to include on this page
3107 * @return array Array of javascript config vars
3110 public function getJsConfigVars() {
3111 return $this->mJsConfigVars
;
3115 * Add one or more variables to be set in mw.config in JavaScript
3117 * @param string|array $keys Key or array of key/value pairs
3118 * @param mixed $value [optional] Value of the configuration variable
3120 public function addJsConfigVars( $keys, $value = null ) {
3121 if ( is_array( $keys ) ) {
3122 foreach ( $keys as $key => $value ) {
3123 $this->mJsConfigVars
[$key] = $value;
3128 $this->mJsConfigVars
[$keys] = $value;
3132 * Get an array containing the variables to be set in mw.config in JavaScript.
3134 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3135 * - in other words, page-independent/site-wide variables (without state).
3136 * You will only be adding bloat to the html page and causing page caches to
3137 * have to be purged on configuration changes.
3140 private function getJSVars() {
3145 $canonicalSpecialPageName = false; # bug 21115
3147 $title = $this->getTitle();
3148 $ns = $title->getNamespace();
3149 $canonicalNamespace = MWNamespace
::exists( $ns )
3150 ? MWNamespace
::getCanonicalName( $ns )
3151 : $title->getNsText();
3153 $sk = $this->getSkin();
3154 // Get the relevant title so that AJAX features can use the correct page name
3155 // when making API requests from certain special pages (bug 34972).
3156 $relevantTitle = $sk->getRelevantTitle();
3157 $relevantUser = $sk->getRelevantUser();
3159 if ( $ns == NS_SPECIAL
) {
3160 list( $canonicalSpecialPageName, /*...*/ ) =
3161 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3162 } elseif ( $this->canUseWikiPage() ) {
3163 $wikiPage = $this->getWikiPage();
3164 $curRevisionId = $wikiPage->getLatest();
3165 $articleId = $wikiPage->getId();
3168 $lang = $title->getPageLanguage();
3170 // Pre-process information
3171 $separatorTransTable = $lang->separatorTransformTable();
3172 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3173 $compactSeparatorTransTable = array(
3174 implode( "\t", array_keys( $separatorTransTable ) ),
3175 implode( "\t", $separatorTransTable ),
3177 $digitTransTable = $lang->digitTransformTable();
3178 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3179 $compactDigitTransTable = array(
3180 implode( "\t", array_keys( $digitTransTable ) ),
3181 implode( "\t", $digitTransTable ),
3184 $user = $this->getUser();
3187 'wgCanonicalNamespace' => $canonicalNamespace,
3188 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3189 'wgNamespaceNumber' => $title->getNamespace(),
3190 'wgPageName' => $title->getPrefixedDBkey(),
3191 'wgTitle' => $title->getText(),
3192 'wgCurRevisionId' => $curRevisionId,
3193 'wgRevisionId' => (int)$this->getRevisionId(),
3194 'wgArticleId' => $articleId,
3195 'wgIsArticle' => $this->isArticle(),
3196 'wgIsRedirect' => $title->isRedirect(),
3197 'wgAction' => Action
::getActionName( $this->getContext() ),
3198 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3199 'wgUserGroups' => $user->getEffectiveGroups(),
3200 'wgCategories' => $this->getCategories(),
3201 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3202 'wgPageContentLanguage' => $lang->getCode(),
3203 'wgPageContentModel' => $title->getContentModel(),
3204 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3205 'wgDigitTransformTable' => $compactDigitTransTable,
3206 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3207 'wgMonthNames' => $lang->getMonthNamesArray(),
3208 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3209 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3210 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3213 if ( $user->isLoggedIn() ) {
3214 $vars['wgUserId'] = $user->getId();
3215 $vars['wgUserEditCount'] = $user->getEditCount();
3216 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3217 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3218 // Get the revision ID of the oldest new message on the user's talk
3219 // page. This can be used for constructing new message alerts on
3221 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3224 if ( $wgContLang->hasVariants() ) {
3225 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3227 // Same test as SkinTemplate
3228 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3229 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3231 foreach ( $title->getRestrictionTypes() as $type ) {
3232 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3235 if ( $title->isMainPage() ) {
3236 $vars['wgIsMainPage'] = true;
3239 if ( $this->mRedirectedFrom
) {
3240 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3243 if ( $relevantUser ) {
3244 $vars['wgRelevantUserName'] = $relevantUser->getName();
3247 // Allow extensions to add their custom variables to the mw.config map.
3248 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3249 // page-dependant but site-wide (without state).
3250 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3251 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3253 // Merge in variables from addJsConfigVars last
3254 return array_merge( $vars, $this->getJsConfigVars() );
3258 * To make it harder for someone to slip a user a fake
3259 * user-JavaScript or user-CSS preview, a random token
3260 * is associated with the login session. If it's not
3261 * passed back with the preview request, we won't render
3266 public function userCanPreview() {
3267 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3268 ||
!$this->getRequest()->wasPosted()
3269 ||
!$this->getUser()->matchEditToken(
3270 $this->getRequest()->getVal( 'wpEditToken' ) )
3274 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3278 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3282 * @return array Array in format "link name or number => 'link html'".
3284 public function getHeadLinksArray() {
3288 $config = $this->getConfig();
3290 $canonicalUrl = $this->mCanonicalUrl
;
3292 $tags['meta-generator'] = Html
::element( 'meta', array(
3293 'name' => 'generator',
3294 'content' => "MediaWiki $wgVersion",
3297 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3298 if ( $p !== 'index,follow' ) {
3299 // http://www.robotstxt.org/wc/meta-user.html
3300 // Only show if it's different from the default robots policy
3301 $tags['meta-robots'] = Html
::element( 'meta', array(
3307 foreach ( $this->mMetatags
as $tag ) {
3308 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3310 $tag[0] = substr( $tag[0], 5 );
3314 $tagName = "meta-{$tag[0]}";
3315 if ( isset( $tags[$tagName] ) ) {
3316 $tagName .= $tag[1];
3318 $tags[$tagName] = Html
::element( 'meta',
3321 'content' => $tag[1]
3326 foreach ( $this->mLinktags
as $tag ) {
3327 $tags[] = Html
::element( 'link', $tag );
3330 # Universal edit button
3331 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3332 $user = $this->getUser();
3333 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3334 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3335 // Original UniversalEditButton
3336 $msg = $this->msg( 'edit' )->text();
3337 $tags['universal-edit-button'] = Html
::element( 'link', array(
3338 'rel' => 'alternate',
3339 'type' => 'application/x-wiki',
3341 'href' => $this->getTitle()->getEditURL(),
3343 // Alternate edit link
3344 $tags['alternative-edit'] = Html
::element( 'link', array(
3347 'href' => $this->getTitle()->getEditURL(),
3352 # Generally the order of the favicon and apple-touch-icon links
3353 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3354 # uses whichever one appears later in the HTML source. Make sure
3355 # apple-touch-icon is specified first to avoid this.
3356 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3357 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3358 'rel' => 'apple-touch-icon',
3359 'href' => $config->get( 'AppleTouchIcon' )
3363 if ( $config->get( 'Favicon' ) !== false ) {
3364 $tags['favicon'] = Html
::element( 'link', array(
3365 'rel' => 'shortcut icon',
3366 'href' => $config->get( 'Favicon' )
3370 # OpenSearch description link
3371 $tags['opensearch'] = Html
::element( 'link', array(
3373 'type' => 'application/opensearchdescription+xml',
3374 'href' => wfScript( 'opensearch_desc' ),
3375 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3378 if ( $config->get( 'EnableAPI' ) ) {
3379 # Real Simple Discovery link, provides auto-discovery information
3380 # for the MediaWiki API (and potentially additional custom API
3381 # support such as WordPress or Twitter-compatible APIs for a
3382 # blogging extension, etc)
3383 $tags['rsd'] = Html
::element( 'link', array(
3385 'type' => 'application/rsd+xml',
3386 // Output a protocol-relative URL here if $wgServer is protocol-relative
3387 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3388 'href' => wfExpandUrl( wfAppendQuery(
3390 array( 'action' => 'rsd' ) ),
3397 if ( !$config->get( 'DisableLangConversion' ) ) {
3398 $lang = $this->getTitle()->getPageLanguage();
3399 if ( $lang->hasVariants() ) {
3400 $variants = $lang->getVariants();
3401 foreach ( $variants as $_v ) {
3402 $tags["variant-$_v"] = Html
::element( 'link', array(
3403 'rel' => 'alternate',
3404 'hreflang' => wfBCP47( $_v ),
3405 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3409 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3410 $tags["variant-x-default"] = Html
::element( 'link', array(
3411 'rel' => 'alternate',
3412 'hreflang' => 'x-default',
3413 'href' => $this->getTitle()->getLocalURL() ) );
3418 if ( $config->get( 'RightsPage' ) ) {
3419 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3422 $copyright = $copy->getLocalURL();
3426 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3427 $copyright = $config->get( 'RightsUrl' );
3431 $tags['copyright'] = Html
::element( 'link', array(
3432 'rel' => 'copyright',
3433 'href' => $copyright )
3438 if ( $config->get( 'Feed' ) ) {
3439 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3440 # Use the page name for the title. In principle, this could
3441 # lead to issues with having the same name for different feeds
3442 # corresponding to the same page, but we can't avoid that at
3445 $tags[] = $this->feedLink(
3448 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3449 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3453 # Recent changes feed should appear on every page (except recentchanges,
3454 # that would be redundant). Put it after the per-page feed to avoid
3455 # changing existing behavior. It's still available, probably via a
3456 # menu in your browser. Some sites might have a different feed they'd
3457 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3458 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3459 # If so, use it instead.
3460 $sitename = $config->get( 'Sitename' );
3461 if ( $config->get( 'OverrideSiteFeed' ) ) {
3462 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3463 // Note, this->feedLink escapes the url.
3464 $tags[] = $this->feedLink(
3467 $this->msg( "site-{$type}-feed", $sitename )->text()
3470 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3471 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3472 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3473 $tags[] = $this->feedLink(
3475 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3476 # For grep: 'site-rss-feed', 'site-atom-feed'
3477 $this->msg( "site-{$format}-feed", $sitename )->text()
3484 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3485 if ( $canonicalUrl !== false ) {
3486 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3488 $reqUrl = $this->getRequest()->getRequestURL();
3489 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3492 if ( $canonicalUrl !== false ) {
3493 $tags[] = Html
::element( 'link', array(
3494 'rel' => 'canonical',
3495 'href' => $canonicalUrl
3503 * @return string HTML tag links to be put in the header.
3504 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3505 * OutputPage::getHeadLinksArray directly.
3507 public function getHeadLinks() {
3508 wfDeprecated( __METHOD__
, '1.24' );
3509 return implode( "\n", $this->getHeadLinksArray() );
3513 * Generate a "<link rel/>" for a feed.
3515 * @param string $type Feed type
3516 * @param string $url URL to the feed
3517 * @param string $text Value of the "title" attribute
3518 * @return string HTML fragment
3520 private function feedLink( $type, $url, $text ) {
3521 return Html
::element( 'link', array(
3522 'rel' => 'alternate',
3523 'type' => "application/$type+xml",
3530 * Add a local or specified stylesheet, with the given media options.
3531 * Meant primarily for internal use...
3533 * @param string $style URL to the file
3534 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3535 * @param string $condition For IE conditional comments, specifying an IE version
3536 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3538 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3540 // Even though we expect the media type to be lowercase, but here we
3541 // force it to lowercase to be safe.
3543 $options['media'] = $media;
3546 $options['condition'] = $condition;
3549 $options['dir'] = $dir;
3551 $this->styles
[$style] = $options;
3555 * Adds inline CSS styles
3556 * @param mixed $style_css Inline CSS
3557 * @param string $flip Set to 'flip' to flip the CSS if needed
3559 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3560 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3561 # If wanted, and the interface is right-to-left, flip the CSS
3562 $style_css = CSSJanus
::transform( $style_css, true, false );
3564 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3568 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3569 * These will be applied to various media & IE conditionals.
3573 public function buildCssLinks() {
3576 $this->getSkin()->setupSkinUserCss( $this );
3578 // Add ResourceLoader styles
3579 // Split the styles into these groups
3584 'private' => array(),
3585 'noscript' => array()
3588 $otherTags = ''; // Tags to append after the normal <link> tags
3589 $resourceLoader = $this->getResourceLoader();
3591 $moduleStyles = $this->getModuleStyles();
3593 // Per-site custom styles
3594 $moduleStyles[] = 'site';
3595 $moduleStyles[] = 'noscript';
3596 $moduleStyles[] = 'user.groups';
3598 // Per-user custom styles
3599 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3600 && $this->userCanPreview()
3602 // We're on a preview of a CSS subpage
3603 // Exclude this page from the user module in case it's in there (bug 26283)
3604 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3605 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3607 $otherTags .= $link['html'];
3609 // Load the previewed CSS
3610 // If needed, Janus it first. This is user-supplied CSS, so it's
3611 // assumed to be right for the content language directionality.
3612 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3613 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3614 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3616 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3618 // Load the user styles normally
3619 $moduleStyles[] = 'user';
3622 // Per-user preference styles
3623 $moduleStyles[] = 'user.cssprefs';
3625 foreach ( $moduleStyles as $name ) {
3626 $module = $resourceLoader->getModule( $name );
3630 $group = $module->getGroup();
3631 // Modules in groups different than the ones listed on top (see $styles assignment)
3632 // will be placed in the "other" group
3633 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3636 // We want site, private and user styles to override dynamically added
3637 // styles from modules, but we want dynamically added styles to override
3638 // statically added styles from other modules. So the order has to be
3639 // other, dynamic, site, private, user. Add statically added styles for
3641 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3642 // Add normal styles added through addStyle()/addInlineStyle() here
3643 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3644 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3645 // We use a <meta> tag with a made-up name for this because that's valid HTML
3646 $links[] = Html
::element(
3648 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3651 // Add site, private and user styles
3652 // 'private' at present only contains user.options, so put that before 'user'
3653 // Any future private modules will likely have a similar user-specific character
3654 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3655 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3656 ResourceLoaderModule
::TYPE_STYLES
3660 // Add stuff in $otherTags (previewed user CSS if applicable)
3661 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3667 public function buildCssLinksArray() {
3670 // Add any extension CSS
3671 foreach ( $this->mExtStyles
as $url ) {
3672 $this->addStyle( $url );
3674 $this->mExtStyles
= array();
3676 foreach ( $this->styles
as $file => $options ) {
3677 $link = $this->styleLink( $file, $options );
3679 $links[$file] = $link;
3686 * Generate \<link\> tags for stylesheets
3688 * @param string $style URL to the file
3689 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3690 * @return string HTML fragment
3692 protected function styleLink( $style, array $options ) {
3693 if ( isset( $options['dir'] ) ) {
3694 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3699 if ( isset( $options['media'] ) ) {
3700 $media = self
::transformCssMedia( $options['media'] );
3701 if ( is_null( $media ) ) {
3708 if ( substr( $style, 0, 1 ) == '/' ||
3709 substr( $style, 0, 5 ) == 'http:' ||
3710 substr( $style, 0, 6 ) == 'https:' ) {
3713 $config = $this->getConfig();
3714 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3717 $link = Html
::linkedStyle( $url, $media );
3719 if ( isset( $options['condition'] ) ) {
3720 $condition = htmlspecialchars( $options['condition'] );
3721 $link = "<!--[if $condition]>$link<![endif]-->";
3727 * Transform "media" attribute based on request parameters
3729 * @param string $media Current value of the "media" attribute
3730 * @return string Modified value of the "media" attribute, or null to skip
3733 public static function transformCssMedia( $media ) {
3736 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3737 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3739 // Switch in on-screen display for media testing
3741 'printable' => 'print',
3742 'handheld' => 'handheld',
3744 foreach ( $switches as $switch => $targetMedia ) {
3745 if ( $wgRequest->getBool( $switch ) ) {
3746 if ( $media == $targetMedia ) {
3748 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3749 // This regex will not attempt to understand a comma-separated media_query_list
3751 // Example supported values for $media:
3752 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3753 // Example NOT supported value for $media:
3754 // '3d-glasses, screen, print and resolution > 90dpi'
3756 // If it's a print request, we never want any kind of screen stylesheets
3757 // If it's a handheld request (currently the only other choice with a switch),
3758 // we don't want simple 'screen' but we might want screen queries that
3759 // have a max-width or something, so we'll pass all others on and let the
3760 // client do the query.
3761 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3772 * Add a wikitext-formatted message to the output.
3773 * This is equivalent to:
3775 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3777 public function addWikiMsg( /*...*/ ) {
3778 $args = func_get_args();
3779 $name = array_shift( $args );
3780 $this->addWikiMsgArray( $name, $args );
3784 * Add a wikitext-formatted message to the output.
3785 * Like addWikiMsg() except the parameters are taken as an array
3786 * instead of a variable argument list.
3788 * @param string $name
3789 * @param array $args
3791 public function addWikiMsgArray( $name, $args ) {
3792 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3796 * This function takes a number of message/argument specifications, wraps them in
3797 * some overall structure, and then parses the result and adds it to the output.
3799 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3800 * on. The subsequent arguments may either be strings, in which case they are the
3801 * message names, or arrays, in which case the first element is the message name,
3802 * and subsequent elements are the parameters to that message.
3804 * Don't use this for messages that are not in users interface language.
3808 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3812 * $wgOut->addWikiText( "<div class='error'>\n"
3813 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3815 * The newline after opening div is needed in some wikitext. See bug 19226.
3817 * @param string $wrap
3819 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3820 $msgSpecs = func_get_args();
3821 array_shift( $msgSpecs );
3822 $msgSpecs = array_values( $msgSpecs );
3824 foreach ( $msgSpecs as $n => $spec ) {
3825 if ( is_array( $spec ) ) {
3827 $name = array_shift( $args );
3828 if ( isset( $args['options'] ) ) {
3829 unset( $args['options'] );
3831 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3839 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3841 $this->addWikiText( $s );
3845 * Include jQuery core. Use this to avoid loading it multiple times
3846 * before we get a usable script loader.
3848 * @param array $modules List of jQuery modules which should be loaded
3849 * @return array The list of modules which were not loaded.
3851 * @deprecated since 1.17
3853 public function includeJQuery( array $modules = array() ) {
3858 * Enables/disables TOC, doesn't override __NOTOC__
3862 public function enableTOC( $flag = true ) {
3863 $this->mEnableTOC
= $flag;
3870 public function isTOCEnabled() {
3871 return $this->mEnableTOC
;
3875 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3879 public function enableSectionEditLinks( $flag = true ) {
3880 $this->mEnableSectionEditLinks
= $flag;
3887 public function sectionEditLinksEnabled() {
3888 return $this->mEnableSectionEditLinks
;