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();
125 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
126 private $mLanguageLinks = array();
129 * Used for JavaScript (pre resource loader)
130 * @todo We should split JS / CSS.
131 * mScripts content is inserted as is in "<head>" by Skin. This might
132 * contain either a link to a stylesheet or inline CSS.
134 private $mScripts = '';
136 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
137 protected $mInlineStyles = '';
140 private $mLinkColours;
143 * @var string Used by skin template.
144 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
146 public $mPageLinkTitle = '';
148 /** @var array Array of elements in "<head>". Parser might add its own headers! */
149 protected $mHeadItems = array();
151 // @todo FIXME: Next 5 variables probably come from the resource loader
154 protected $mModules = array();
157 protected $mModuleScripts = array();
160 protected $mModuleStyles = array();
163 protected $mModuleMessages = array();
165 /** @var ResourceLoader */
166 protected $mResourceLoader;
169 protected $mJsConfigVars = array();
172 protected $mTemplateIds = array();
175 protected $mImageTimeKeys = array();
178 public $mRedirectCode = '';
180 protected $mFeedLinksAppendQuery = null;
184 * The level of 'untrustworthiness' allowed for modules loaded on this page.
185 * @see ResourceLoaderModule::$origin
187 protected $mAllowedModuleOrigin = ResourceLoaderModule
::ORIGIN_ALL
;
189 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
190 protected $mDoNothing = false;
198 private $mContainsOldMagic = 0;
201 protected $mContainsNewMagic = 0;
204 * lazy initialised, use parserOptions()
207 protected $mParserOptions = null;
210 * Handles the Atom / RSS links.
211 * We probably only support Atom in 2011.
212 * @see $wgAdvertisedFeedTypes
214 private $mFeedLinks = array();
216 // Gwicke work on squid caching? Roughly from 2003.
217 protected $mEnableClientCache = true;
219 /** @var bool Flag if output should only contain the body of the article. */
220 private $mArticleBodyOnly = false;
223 protected $mNewSectionLink = false;
226 protected $mHideNewSectionLink = false;
229 * @var bool Comes from the parser. This was probably made to load CSS/JS
230 * only if we had "<gallery>". Used directly in CategoryPage.php.
231 * Looks like resource loader can replace this.
233 public $mNoGallery = false;
236 private $mPageTitleActionText = '';
239 private $mParseWarnings = array();
241 /** @var int Cache stuff. Looks like mEnableClientCache */
242 protected $mSquidMaxage = 0;
248 protected $mPreventClickjacking = true;
250 /** @var int To include the variable {{REVISIONID}} */
251 private $mRevisionId = null;
254 private $mRevisionTimestamp = null;
257 protected $mFileVersion = null;
260 * @var array An array of stylesheet filenames (relative from skins path),
261 * with options for CSS media, IE conditions, and RTL/LTR direction.
262 * For internal use; add settings in the skin via $this->addStyle()
264 * Style again! This seems like a code duplication since we already have
265 * mStyles. This is what makes Open Source amazing.
267 protected $styles = array();
270 * Whether jQuery is already handled.
272 protected $mJQueryDone = false;
274 private $mIndexPolicy = 'index';
275 private $mFollowPolicy = 'follow';
276 private $mVaryHeader = array(
277 'Accept-Encoding' => array( 'list-contains=gzip' ),
281 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
286 private $mRedirectedFrom = null;
289 * Additional key => value data
291 private $mProperties = array();
294 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
296 private $mTarget = null;
299 * @var bool Whether parser output should contain table of contents
301 private $mEnableTOC = true;
304 * @var bool Whether parser output should contain section edit links
306 private $mEnableSectionEditLinks = true;
309 * Constructor for OutputPage. This should not be called directly.
310 * Instead a new RequestContext should be created and it will implicitly create
311 * a OutputPage tied to that context.
312 * @param IContextSource|null $context
314 function __construct( IContextSource
$context = null ) {
315 if ( $context === null ) {
316 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
317 wfDeprecated( __METHOD__
, '1.18' );
319 $this->setContext( $context );
324 * Redirect to $url rather than displaying the normal page
326 * @param string $url URL
327 * @param string $responsecode HTTP status code
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect
= str_replace( "\n", '', $url );
332 $this->mRedirectCode
= $responsecode;
336 * Get the URL to redirect to, or an empty string if not redirect URL set
340 public function getRedirect() {
341 return $this->mRedirect
;
345 * Set the HTTP status code to send with the output.
347 * @param int $statusCode
349 public function setStatusCode( $statusCode ) {
350 $this->mStatusCode
= $statusCode;
354 * Add a new "<meta>" tag
355 * To add an http-equiv meta tag, precede the name with "http:"
357 * @param string $name Tag name
358 * @param string $val Tag value
360 function addMeta( $name, $val ) {
361 array_push( $this->mMetatags
, array( $name, $val ) );
365 * Add a new \<link\> tag to the page header.
367 * Note: use setCanonicalUrl() for rel=canonical.
369 * @param array $linkarr Associative array of attributes.
371 function addLink( array $linkarr ) {
372 array_push( $this->mLinktags
, $linkarr );
376 * Add a new \<link\> with "rel" attribute set to "meta"
378 * @param array $linkarr Associative array mapping attribute names to their
379 * values, both keys and values will be escaped, and the
380 * "rel" attribute will be automatically added
382 function addMetadataLink( array $linkarr ) {
383 $linkarr['rel'] = $this->getMetadataAttribute();
384 $this->addLink( $linkarr );
388 * Set the URL to be used for the <link rel=canonical>. This should be used
389 * in preference to addLink(), to avoid duplicate link tags.
392 function setCanonicalUrl( $url ) {
393 $this->mCanonicalUrl
= $url;
397 * Get the value of the "rel" attribute for metadata links
401 public function getMetadataAttribute() {
402 # note: buggy CC software only reads first "meta" link
403 static $haveMeta = false;
405 return 'alternate meta';
413 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
415 * @param string $script Raw HTML
417 function addScript( $script ) {
418 $this->mScripts
.= $script . "\n";
422 * Register and add a stylesheet from an extension directory.
424 * @param string $url Path to sheet. Provide either a full url (beginning
425 * with 'http', etc) or a relative path from the document root
426 * (beginning with '/'). Otherwise it behaves identically to
427 * addStyle() and draws from the /skins folder.
429 public function addExtensionStyle( $url ) {
430 array_push( $this->mExtStyles
, $url );
434 * Get all styles added by extensions
438 function getExtStyle() {
439 return $this->mExtStyles
;
443 * Add a JavaScript file out of skins/common, or a given relative path.
445 * @param string $file Filename in skins/common or complete on-server path
447 * @param string $version Style version of the file. Defaults to $wgStyleVersion
449 public function addScriptFile( $file, $version = null ) {
450 // See if $file parameter is an absolute URL or begins with a slash
451 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
454 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
456 if ( is_null( $version ) ) {
457 $version = $this->getConfig()->get( 'StyleVersion' );
459 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
463 * Add a self-contained script tag with the given contents
465 * @param string $script JavaScript text, no "<script>" tags
467 public function addInlineScript( $script ) {
468 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
472 * Get all registered JS and CSS tags for the header.
475 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
477 function getScript() {
478 wfDeprecated( __METHOD__
, '1.24' );
479 return $this->mScripts
. $this->getHeadItems();
483 * Filter an array of modules to remove insufficiently trustworthy members, and modules
484 * which are no longer registered (eg a page is cached before an extension is disabled)
485 * @param array $modules
486 * @param string|null $position If not null, only return modules with this position
487 * @param string $type
490 protected function filterModules( array $modules, $position = null,
491 $type = ResourceLoaderModule
::TYPE_COMBINED
493 $resourceLoader = $this->getResourceLoader();
494 $filteredModules = array();
495 foreach ( $modules as $val ) {
496 $module = $resourceLoader->getModule( $val );
497 if ( $module instanceof ResourceLoaderModule
498 && $module->getOrigin() <= $this->getAllowedModules( $type )
499 && ( is_null( $position ) ||
$module->getPosition() == $position )
500 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
502 $filteredModules[] = $val;
505 return $filteredModules;
509 * Get the list of modules to include on this page
511 * @param bool $filter Whether to filter out insufficiently trustworthy modules
512 * @param string|null $position If not null, only return modules with this position
513 * @param string $param
514 * @return array Array of module names
516 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
517 $modules = array_values( array_unique( $this->$param ) );
519 ?
$this->filterModules( $modules, $position )
524 * Add one or more modules recognized by the resource loader. Modules added
525 * through this function will be loaded by the resource loader when the
528 * @param string|array $modules Module name (string) or array of module names
530 public function addModules( $modules ) {
531 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
535 * Get the list of module JS to include on this page
537 * @param bool $filter
538 * @param string|null $position
540 * @return array Array of module names
542 public function getModuleScripts( $filter = false, $position = null ) {
543 return $this->getModules( $filter, $position, 'mModuleScripts' );
547 * Add only JS of one or more modules recognized by the resource loader. Module
548 * scripts added through this function will be loaded by the resource loader when
551 * @param string|array $modules Module name (string) or array of module names
553 public function addModuleScripts( $modules ) {
554 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
558 * Get the list of module CSS to include on this page
560 * @param bool $filter
561 * @param string|null $position
563 * @return array Array of module names
565 public function getModuleStyles( $filter = false, $position = null ) {
566 return $this->getModules( $filter, $position, 'mModuleStyles' );
570 * Add only CSS of one or more modules recognized by the resource loader.
572 * Module styles added through this function will be added using standard link CSS
573 * tags, rather than as a combined Javascript and CSS package. Thus, they will
574 * load when JavaScript is disabled (unless CSS also happens to be disabled).
576 * @param string|array $modules Module name (string) or array of module names
578 public function addModuleStyles( $modules ) {
579 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
583 * Get the list of module messages to include on this page
585 * @param bool $filter
586 * @param string|null $position
588 * @return array Array of module names
590 public function getModuleMessages( $filter = false, $position = null ) {
591 return $this->getModules( $filter, $position, 'mModuleMessages' );
595 * Add only messages of one or more modules recognized by the resource loader.
596 * Module messages added through this function will be loaded by the resource
597 * loader when the page loads.
599 * @param string|array $modules Module name (string) or array of module names
601 public function addModuleMessages( $modules ) {
602 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
606 * @return null|string ResourceLoader target
608 public function getTarget() {
609 return $this->mTarget
;
613 * Sets ResourceLoader target for load.php links. If null, will be omitted
615 * @param string|null $target
617 public function setTarget( $target ) {
618 $this->mTarget
= $target;
622 * Get an array of head items
626 function getHeadItemsArray() {
627 return $this->mHeadItems
;
631 * Get all header items in a string
634 * @deprecated since 1.24 Use OutputPage::headElement or
635 * if absolutely necessary use OutputPage::getHeadItemsArray
637 function getHeadItems() {
638 wfDeprecated( __METHOD__
, '1.24' );
640 foreach ( $this->mHeadItems
as $item ) {
647 * Add or replace an header item to the output
649 * @param string $name Item name
650 * @param string $value Raw HTML
652 public function addHeadItem( $name, $value ) {
653 $this->mHeadItems
[$name] = $value;
657 * Check if the header item $name is already set
659 * @param string $name Item name
662 public function hasHeadItem( $name ) {
663 return isset( $this->mHeadItems
[$name] );
667 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
669 * @param string $tag Value of "ETag" header
671 function setETag( $tag ) {
676 * Set whether the output should only contain the body of the article,
677 * without any skin, sidebar, etc.
678 * Used e.g. when calling with "action=render".
680 * @param bool $only Whether to output only the body of the article
682 public function setArticleBodyOnly( $only ) {
683 $this->mArticleBodyOnly
= $only;
687 * Return whether the output will contain only the body of the article
691 public function getArticleBodyOnly() {
692 return $this->mArticleBodyOnly
;
696 * Set an additional output property
699 * @param string $name
700 * @param mixed $value
702 public function setProperty( $name, $value ) {
703 $this->mProperties
[$name] = $value;
707 * Get an additional output property
710 * @param string $name
711 * @return mixed Property value or null if not found
713 public function getProperty( $name ) {
714 if ( isset( $this->mProperties
[$name] ) ) {
715 return $this->mProperties
[$name];
722 * checkLastModified tells the client to use the client-cached page if
723 * possible. If successful, the OutputPage is disabled so that
724 * any future call to OutputPage->output() have no effect.
726 * Side effect: sets mLastModified for Last-Modified header
728 * @param string $timestamp
730 * @return bool True if cache-ok headers was sent.
732 public function checkLastModified( $timestamp ) {
733 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
734 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
737 $config = $this->getConfig();
738 if ( !$config->get( 'CachePages' ) ) {
739 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
743 $timestamp = wfTimestamp( TS_MW
, $timestamp );
744 $modifiedTimes = array(
745 'page' => $timestamp,
746 'user' => $this->getUser()->getTouched(),
747 'epoch' => $config->get( 'CacheEpoch' )
749 if ( $config->get( 'UseSquid' ) ) {
750 // bug 44570: the core page itself may not change, but resources might
751 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
753 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
755 $maxModified = max( $modifiedTimes );
756 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
758 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
759 if ( $clientHeader === false ) {
760 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
764 # IE sends sizes after the date like this:
765 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
766 # this breaks strtotime().
767 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
769 wfSuppressWarnings(); // E_STRICT system time bitching
770 $clientHeaderTime = strtotime( $clientHeader );
772 if ( !$clientHeaderTime ) {
774 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
777 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
781 foreach ( $modifiedTimes as $name => $value ) {
782 if ( $info !== '' ) {
785 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
788 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
789 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
790 wfDebug( __METHOD__
. ": effective Last-Modified: " .
791 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
792 if ( $clientHeaderTime < $maxModified ) {
793 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
798 # Give a 304 response code and disable body output
799 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
800 ini_set( 'zlib.output_compression', 0 );
801 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
802 $this->sendCacheControl();
805 // Don't output a compressed blob when using ob_gzhandler;
806 // it's technically against HTTP spec and seems to confuse
807 // Firefox when the response gets split over two packets.
808 wfClearOutputBuffers();
814 * Override the last modified timestamp
816 * @param string $timestamp New timestamp, in a format readable by
819 public function setLastModified( $timestamp ) {
820 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
824 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
826 * @param string $policy The literal string to output as the contents of
827 * the meta tag. Will be parsed according to the spec and output in
831 public function setRobotPolicy( $policy ) {
832 $policy = Article
::formatRobotPolicy( $policy );
834 if ( isset( $policy['index'] ) ) {
835 $this->setIndexPolicy( $policy['index'] );
837 if ( isset( $policy['follow'] ) ) {
838 $this->setFollowPolicy( $policy['follow'] );
843 * Set the index policy for the page, but leave the follow policy un-
846 * @param string $policy Either 'index' or 'noindex'.
849 public function setIndexPolicy( $policy ) {
850 $policy = trim( $policy );
851 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
852 $this->mIndexPolicy
= $policy;
857 * Set the follow policy for the page, but leave the index policy un-
860 * @param string $policy Either 'follow' or 'nofollow'.
863 public function setFollowPolicy( $policy ) {
864 $policy = trim( $policy );
865 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
866 $this->mFollowPolicy
= $policy;
871 * Set the new value of the "action text", this will be added to the
872 * "HTML title", separated from it with " - ".
874 * @param string $text New value of the "action text"
876 public function setPageTitleActionText( $text ) {
877 $this->mPageTitleActionText
= $text;
881 * Get the value of the "action text"
885 public function getPageTitleActionText() {
886 return $this->mPageTitleActionText
;
890 * "HTML title" means the contents of "<title>".
891 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
893 * @param string|Message $name
895 public function setHTMLTitle( $name ) {
896 if ( $name instanceof Message
) {
897 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
899 $this->mHTMLtitle
= $name;
904 * Return the "HTML title", i.e. the content of the "<title>" tag.
908 public function getHTMLTitle() {
909 return $this->mHTMLtitle
;
913 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
917 public function setRedirectedFrom( $t ) {
918 $this->mRedirectedFrom
= $t;
922 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
923 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
924 * but not bad tags like \<script\>. This function automatically sets
925 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
926 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
927 * good tags like \<i\> will be dropped entirely.
929 * @param string|Message $name
931 public function setPageTitle( $name ) {
932 if ( $name instanceof Message
) {
933 $name = $name->setContext( $this->getContext() )->text();
936 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
937 # but leave "<i>foobar</i>" alone
938 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
939 $this->mPagetitle
= $nameWithTags;
941 # change "<i>foo&bar</i>" to "foo&bar"
943 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
944 ->inContentLanguage()
949 * Return the "page title", i.e. the content of the \<h1\> tag.
953 public function getPageTitle() {
954 return $this->mPagetitle
;
958 * Set the Title object to use
962 public function setTitle( Title
$t ) {
963 $this->getContext()->setTitle( $t );
967 * Replace the subtitle with $str
969 * @param string|Message $str New value of the subtitle. String should be safe HTML.
971 public function setSubtitle( $str ) {
972 $this->clearSubtitle();
973 $this->addSubtitle( $str );
977 * Add $str to the subtitle
979 * @deprecated since 1.19; use addSubtitle() instead
980 * @param string|Message $str String or Message to add to the subtitle
982 public function appendSubtitle( $str ) {
983 $this->addSubtitle( $str );
987 * Add $str to the subtitle
989 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
991 public function addSubtitle( $str ) {
992 if ( $str instanceof Message
) {
993 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
995 $this->mSubtitle
[] = $str;
1000 * Add a subtitle containing a backlink to a page
1002 * @param Title $title Title to link to
1003 * @param array $query Array of additional parameters to include in the link
1005 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1006 if ( $title->isRedirect() ) {
1007 $query['redirect'] = 'no';
1009 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1010 ->rawParams( Linker
::link( $title, null, array(), $query ) ) );
1014 * Clear the subtitles
1016 public function clearSubtitle() {
1017 $this->mSubtitle
= array();
1025 public function getSubtitle() {
1026 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1030 * Set the page as printable, i.e. it'll be displayed with with all
1031 * print styles included
1033 public function setPrintable() {
1034 $this->mPrintable
= true;
1038 * Return whether the page is "printable"
1042 public function isPrintable() {
1043 return $this->mPrintable
;
1047 * Disable output completely, i.e. calling output() will have no effect
1049 public function disable() {
1050 $this->mDoNothing
= true;
1054 * Return whether the output will be completely disabled
1058 public function isDisabled() {
1059 return $this->mDoNothing
;
1063 * Show an "add new section" link?
1067 public function showNewSectionLink() {
1068 return $this->mNewSectionLink
;
1072 * Forcibly hide the new section link?
1076 public function forceHideNewSectionLink() {
1077 return $this->mHideNewSectionLink
;
1081 * Add or remove feed links in the page header
1082 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1083 * for the new version
1084 * @see addFeedLink()
1086 * @param bool $show True: add default feeds, false: remove all feeds
1088 public function setSyndicated( $show = true ) {
1090 $this->setFeedAppendQuery( false );
1092 $this->mFeedLinks
= array();
1097 * Add default feeds to the page header
1098 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1099 * for the new version
1100 * @see addFeedLink()
1102 * @param string $val Query to append to feed links or false to output
1105 public function setFeedAppendQuery( $val ) {
1106 $this->mFeedLinks
= array();
1108 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1109 $query = "feed=$type";
1110 if ( is_string( $val ) ) {
1111 $query .= '&' . $val;
1113 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1118 * Add a feed link to the page header
1120 * @param string $format Feed type, should be a key of $wgFeedClasses
1121 * @param string $href URL
1123 public function addFeedLink( $format, $href ) {
1124 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1125 $this->mFeedLinks
[$format] = $href;
1130 * Should we output feed links for this page?
1133 public function isSyndicated() {
1134 return count( $this->mFeedLinks
) > 0;
1138 * Return URLs for each supported syndication format for this page.
1139 * @return array Associating format keys with URLs
1141 public function getSyndicationLinks() {
1142 return $this->mFeedLinks
;
1146 * Will currently always return null
1150 public function getFeedAppendQuery() {
1151 return $this->mFeedLinksAppendQuery
;
1155 * Set whether the displayed content is related to the source of the
1156 * corresponding article on the wiki
1157 * Setting true will cause the change "article related" toggle to true
1161 public function setArticleFlag( $v ) {
1162 $this->mIsarticle
= $v;
1164 $this->mIsArticleRelated
= $v;
1169 * Return whether the content displayed page is related to the source of
1170 * the corresponding article on the wiki
1174 public function isArticle() {
1175 return $this->mIsarticle
;
1179 * Set whether this page is related an article on the wiki
1180 * Setting false will cause the change of "article flag" toggle to false
1184 public function setArticleRelated( $v ) {
1185 $this->mIsArticleRelated
= $v;
1187 $this->mIsarticle
= false;
1192 * Return whether this page is related an article on the wiki
1196 public function isArticleRelated() {
1197 return $this->mIsArticleRelated
;
1201 * Add new language links
1203 * @param array $newLinkArray Associative array mapping language code to the page
1206 public function addLanguageLinks( array $newLinkArray ) {
1207 $this->mLanguageLinks +
= $newLinkArray;
1211 * Reset the language links and add new language links
1213 * @param array $newLinkArray Associative array mapping language code to the page
1216 public function setLanguageLinks( array $newLinkArray ) {
1217 $this->mLanguageLinks
= $newLinkArray;
1221 * Get the list of language links
1223 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1225 public function getLanguageLinks() {
1226 return $this->mLanguageLinks
;
1230 * Add an array of categories, with names in the keys
1232 * @param array $categories Mapping category name => sort key
1234 public function addCategoryLinks( array $categories ) {
1237 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1241 # Add the links to a LinkBatch
1242 $arr = array( NS_CATEGORY
=> $categories );
1243 $lb = new LinkBatch
;
1244 $lb->setArray( $arr );
1246 # Fetch existence plus the hiddencat property
1247 $dbr = wfGetDB( DB_SLAVE
);
1248 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1249 'page_is_redirect', 'page_latest', 'pp_value' );
1251 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1252 $fields[] = 'page_content_model';
1255 $res = $dbr->select( array( 'page', 'page_props' ),
1257 $lb->constructSet( 'page', $dbr ),
1260 array( 'page_props' => array( 'LEFT JOIN', array(
1261 'pp_propname' => 'hiddencat',
1266 # Add the results to the link cache
1267 $lb->addResultToCache( LinkCache
::singleton(), $res );
1269 # Set all the values to 'normal'.
1270 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1272 # Mark hidden categories
1273 foreach ( $res as $row ) {
1274 if ( isset( $row->pp_value
) ) {
1275 $categories[$row->page_title
] = 'hidden';
1279 # Add the remaining categories to the skin
1281 'OutputPageMakeCategoryLinks',
1282 array( &$this, $categories, &$this->mCategoryLinks
) )
1284 foreach ( $categories as $category => $type ) {
1285 $origcategory = $category;
1286 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1290 $wgContLang->findVariantLink( $category, $title, true );
1291 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1294 $text = $wgContLang->convertHtml( $title->getText() );
1295 $this->mCategories
[] = $title->getText();
1296 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1302 * Reset the category links (but not the category list) and add $categories
1304 * @param array $categories Mapping category name => sort key
1306 public function setCategoryLinks( array $categories ) {
1307 $this->mCategoryLinks
= array();
1308 $this->addCategoryLinks( $categories );
1312 * Get the list of category links, in a 2-D array with the following format:
1313 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1314 * hidden categories) and $link a HTML fragment with a link to the category
1319 public function getCategoryLinks() {
1320 return $this->mCategoryLinks
;
1324 * Get the list of category names this page belongs to
1326 * @return array Array of strings
1328 public function getCategories() {
1329 return $this->mCategories
;
1333 * Restrict the page to loading modules bundled the software.
1335 * Disallows the queue to contain any modules which can be modified by wiki
1336 * users to load on this page.
1338 public function disallowUserJs() {
1339 $this->reduceAllowedModuleOrigin( ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
);
1343 * Get the level of JavaScript / CSS untrustworthiness allowed on this page.
1345 * @see ResourceLoaderModule::$origin
1346 * @param string $type Unused: Module origin allowance used to be fragmented by
1347 * ResourceLoaderModule TYPE_ constants.
1348 * @return int ResourceLoaderModule ORIGIN_ class constant
1350 public function getAllowedModules( $type = null ) {
1351 return $this->mAllowedModuleOrigin
;
1355 * Set the highest level of CSS/JS untrustworthiness allowed
1357 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1358 * Use reduceAllowedModuleOrigin() instead.
1360 * @param string $type ResourceLoaderModule TYPE_ constant
1361 * @param int $level ResourceLoaderModule ORIGIN_ constant
1363 public function setAllowedModules( $type, $level ) {
1364 wfDeprecated( __METHOD__
, '1.24' );
1365 $this->reduceAllowedModuleOrigin( $level );
1369 * Limit the highest level of CSS/JS untrustworthiness allowed.
1371 * @deprecated since 1.24 Module allowance is no longer fragmented by content type.
1372 * Use reduceAllowedModuleOrigin() instead.
1374 * @param string $type ResourceLoaderModule TYPE_ constant
1375 * @param int $level ResourceLoaderModule ORIGIN_ class constant
1377 public function reduceAllowedModules( $type, $level ) {
1378 wfDeprecated( __METHOD__
, '1.24' );
1379 $this->reduceAllowedModuleOrigin( $level );
1383 * Limit the highest level of CSS/JS untrustworthiness allowed.
1385 * If passed the same or a higher level than the current level of untrustworthiness set, the
1386 * level will remain unchanged.
1388 * @param int $level ResourceLoaderModule class constant
1390 public function reduceAllowedModuleOrigin( $level ) {
1391 $this->mAllowedModuleOrigin
= min( $this->mAllowedModuleOrigin
, $level );
1395 * Prepend $text to the body HTML
1397 * @param string $text HTML
1399 public function prependHTML( $text ) {
1400 $this->mBodytext
= $text . $this->mBodytext
;
1404 * Append $text to the body HTML
1406 * @param string $text HTML
1408 public function addHTML( $text ) {
1409 $this->mBodytext
.= $text;
1413 * Shortcut for adding an Html::element via addHTML.
1417 * @param string $element
1418 * @param array $attribs
1419 * @param string $contents
1421 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1422 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1426 * Clear the body HTML
1428 public function clearHTML() {
1429 $this->mBodytext
= '';
1435 * @return string HTML
1437 public function getHTML() {
1438 return $this->mBodytext
;
1442 * Get/set the ParserOptions object to use for wikitext parsing
1444 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1445 * current ParserOption object
1446 * @return ParserOptions
1448 public function parserOptions( $options = null ) {
1449 if ( !$this->mParserOptions
) {
1450 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1451 $this->mParserOptions
->setEditSection( false );
1453 return wfSetVar( $this->mParserOptions
, $options );
1457 * Set the revision ID which will be seen by the wiki text parser
1458 * for things such as embedded {{REVISIONID}} variable use.
1460 * @param int|null $revid An positive integer, or null
1461 * @return mixed Previous value
1463 public function setRevisionId( $revid ) {
1464 $val = is_null( $revid ) ?
null : intval( $revid );
1465 return wfSetVar( $this->mRevisionId
, $val );
1469 * Get the displayed revision ID
1473 public function getRevisionId() {
1474 return $this->mRevisionId
;
1478 * Set the timestamp of the revision which will be displayed. This is used
1479 * to avoid a extra DB call in Skin::lastModified().
1481 * @param string|null $timestamp
1482 * @return mixed Previous value
1484 public function setRevisionTimestamp( $timestamp ) {
1485 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1489 * Get the timestamp of displayed revision.
1490 * This will be null if not filled by setRevisionTimestamp().
1492 * @return string|null
1494 public function getRevisionTimestamp() {
1495 return $this->mRevisionTimestamp
;
1499 * Set the displayed file version
1501 * @param File|bool $file
1502 * @return mixed Previous value
1504 public function setFileVersion( $file ) {
1506 if ( $file instanceof File
&& $file->exists() ) {
1507 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1509 return wfSetVar( $this->mFileVersion
, $val, true );
1513 * Get the displayed file version
1515 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1517 public function getFileVersion() {
1518 return $this->mFileVersion
;
1522 * Get the templates used on this page
1524 * @return array (namespace => dbKey => revId)
1527 public function getTemplateIds() {
1528 return $this->mTemplateIds
;
1532 * Get the files used on this page
1534 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1537 public function getFileSearchOptions() {
1538 return $this->mImageTimeKeys
;
1542 * Convert wikitext to HTML and add it to the buffer
1543 * Default assumes that the current page title will be used.
1545 * @param string $text
1546 * @param bool $linestart Is this the start of a line?
1547 * @param bool $interface Is this text in the user interface language?
1549 public function addWikiText( $text, $linestart = true, $interface = true ) {
1550 $title = $this->getTitle(); // Work around E_STRICT
1552 throw new MWException( 'Title is null' );
1554 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1558 * Add wikitext with a custom Title object
1560 * @param string $text Wikitext
1561 * @param Title $title
1562 * @param bool $linestart Is this the start of a line?
1564 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1565 $this->addWikiTextTitle( $text, $title, $linestart );
1569 * Add wikitext with a custom Title object and tidy enabled.
1571 * @param string $text Wikitext
1572 * @param Title $title
1573 * @param bool $linestart Is this the start of a line?
1575 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1576 $this->addWikiTextTitle( $text, $title, $linestart, true );
1580 * Add wikitext with tidy enabled
1582 * @param string $text Wikitext
1583 * @param bool $linestart Is this the start of a line?
1585 public function addWikiTextTidy( $text, $linestart = true ) {
1586 $title = $this->getTitle();
1587 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1591 * Add wikitext with a custom Title object
1593 * @param string $text Wikitext
1594 * @param Title $title
1595 * @param bool $linestart Is this the start of a line?
1596 * @param bool $tidy Whether to use tidy
1597 * @param bool $interface Whether it is an interface message
1598 * (for example disables conversion)
1600 public function addWikiTextTitle( $text, Title
$title, $linestart,
1601 $tidy = false, $interface = false
1605 wfProfileIn( __METHOD__
);
1607 $popts = $this->parserOptions();
1608 $oldTidy = $popts->setTidy( $tidy );
1609 $popts->setInterfaceMessage( (bool)$interface );
1611 $parserOutput = $wgParser->getFreshParser()->parse(
1612 $text, $title, $popts,
1613 $linestart, true, $this->mRevisionId
1616 $popts->setTidy( $oldTidy );
1618 $this->addParserOutput( $parserOutput );
1620 wfProfileOut( __METHOD__
);
1624 * Add a ParserOutput object, but without Html.
1626 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1627 * @param ParserOutput $parserOutput
1629 public function addParserOutputNoText( $parserOutput ) {
1630 $this->addParserOutputMetadata( $parserOutput );
1634 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1635 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1639 * @param ParserOutput $parserOutput
1641 public function addParserOutputMetadata( $parserOutput ) {
1642 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1643 $this->addCategoryLinks( $parserOutput->getCategories() );
1644 $this->mNewSectionLink
= $parserOutput->getNewSection();
1645 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1647 $this->mParseWarnings
= $parserOutput->getWarnings();
1648 if ( !$parserOutput->isCacheable() ) {
1649 $this->enableClientCache( false );
1651 $this->mNoGallery
= $parserOutput->getNoGallery();
1652 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1653 $this->addModules( $parserOutput->getModules() );
1654 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1655 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1656 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1657 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1658 $this->mPreventClickjacking
= $this->mPreventClickjacking
1659 ||
$parserOutput->preventClickjacking();
1661 // Template versioning...
1662 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1663 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1664 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1666 $this->mTemplateIds
[$ns] = $dbks;
1669 // File versioning...
1670 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1671 $this->mImageTimeKeys
[$dbk] = $data;
1674 // Hooks registered in the object
1675 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1676 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1677 list( $hookName, $data ) = $hookInfo;
1678 if ( isset( $parserOutputHooks[$hookName] ) ) {
1679 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1683 // Link flags are ignored for now, but may in the future be
1684 // used to mark individual language links.
1685 $linkFlags = array();
1686 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1687 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1691 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1692 * ParserOutput object, without any other metadata.
1695 * @param ParserOutput $parserOutput
1697 public function addParserOutputContent( $parserOutput ) {
1698 $this->addParserOutputText( $parserOutput );
1700 $this->addModules( $parserOutput->getModules() );
1701 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1702 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1703 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1705 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1709 * Add the HTML associated with a ParserOutput object, without any metadata.
1712 * @param ParserOutput $parserOutput
1714 public function addParserOutputText( $parserOutput ) {
1715 $text = $parserOutput->getText();
1716 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1717 $this->addHTML( $text );
1721 * Add everything from a ParserOutput object.
1723 * @param ParserOutput $parserOutput
1725 function addParserOutput( $parserOutput ) {
1726 $this->addParserOutputMetadata( $parserOutput );
1727 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1729 // Touch section edit links only if not previously disabled
1730 if ( $parserOutput->getEditSectionTokens() ) {
1731 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1734 $this->addParserOutputText( $parserOutput );
1738 * Add the output of a QuickTemplate to the output buffer
1740 * @param QuickTemplate $template
1742 public function addTemplate( &$template ) {
1743 $this->addHTML( $template->getHTML() );
1747 * Parse wikitext and return the HTML.
1749 * @param string $text
1750 * @param bool $linestart Is this the start of a line?
1751 * @param bool $interface Use interface language ($wgLang instead of
1752 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1753 * This also disables LanguageConverter.
1754 * @param Language $language Target language object, will override $interface
1755 * @throws MWException
1756 * @return string HTML
1758 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1761 if ( is_null( $this->getTitle() ) ) {
1762 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1765 $popts = $this->parserOptions();
1767 $popts->setInterfaceMessage( true );
1769 if ( $language !== null ) {
1770 $oldLang = $popts->setTargetLanguage( $language );
1773 $parserOutput = $wgParser->getFreshParser()->parse(
1774 $text, $this->getTitle(), $popts,
1775 $linestart, true, $this->mRevisionId
1779 $popts->setInterfaceMessage( false );
1781 if ( $language !== null ) {
1782 $popts->setTargetLanguage( $oldLang );
1785 return $parserOutput->getText();
1789 * Parse wikitext, strip paragraphs, and return the HTML.
1791 * @param string $text
1792 * @param bool $linestart Is this the start of a line?
1793 * @param bool $interface Use interface language ($wgLang instead of
1794 * $wgContLang) while parsing language sensitive magic
1795 * words like GRAMMAR and PLURAL
1796 * @return string HTML
1798 public function parseInline( $text, $linestart = true, $interface = false ) {
1799 $parsed = $this->parse( $text, $linestart, $interface );
1800 return Parser
::stripOuterParagraph( $parsed );
1804 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1806 * @param int $maxage Maximum cache time on the Squid, in seconds.
1808 public function setSquidMaxage( $maxage ) {
1809 $this->mSquidMaxage
= $maxage;
1813 * Use enableClientCache(false) to force it to send nocache headers
1815 * @param bool $state
1819 public function enableClientCache( $state ) {
1820 return wfSetVar( $this->mEnableClientCache
, $state );
1824 * Get the list of cookies that will influence on the cache
1828 function getCacheVaryCookies() {
1830 if ( $cookies === null ) {
1831 $config = $this->getConfig();
1832 $cookies = array_merge(
1834 $config->get( 'CookiePrefix' ) . 'Token',
1835 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1839 $config->get( 'CacheVaryCookies' )
1841 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1847 * Check if the request has a cache-varying cookie header
1848 * If it does, it's very important that we don't allow public caching
1852 function haveCacheVaryCookies() {
1853 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1854 if ( $cookieHeader === false ) {
1857 $cvCookies = $this->getCacheVaryCookies();
1858 foreach ( $cvCookies as $cookieName ) {
1859 # Check for a simple string match, like the way squid does it
1860 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1861 wfDebug( __METHOD__
. ": found $cookieName\n" );
1865 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1870 * Add an HTTP header that will influence on the cache
1872 * @param string $header Header name
1873 * @param array|null $option
1874 * @todo FIXME: Document the $option parameter; it appears to be for
1875 * X-Vary-Options but what format is acceptable?
1877 public function addVaryHeader( $header, $option = null ) {
1878 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1879 $this->mVaryHeader
[$header] = (array)$option;
1880 } elseif ( is_array( $option ) ) {
1881 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1882 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1884 $this->mVaryHeader
[$header] = $option;
1887 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1891 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1892 * such as Accept-Encoding or Cookie
1896 public function getVaryHeader() {
1897 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1901 * Get a complete X-Vary-Options header
1905 public function getXVO() {
1906 $cvCookies = $this->getCacheVaryCookies();
1908 $cookiesOption = array();
1909 foreach ( $cvCookies as $cookieName ) {
1910 $cookiesOption[] = 'string-contains=' . $cookieName;
1912 $this->addVaryHeader( 'Cookie', $cookiesOption );
1915 foreach ( $this->mVaryHeader
as $header => $option ) {
1916 $newheader = $header;
1917 if ( is_array( $option ) && count( $option ) > 0 ) {
1918 $newheader .= ';' . implode( ';', $option );
1920 $headers[] = $newheader;
1922 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1928 * bug 21672: Add Accept-Language to Vary and XVO headers
1929 * if there's no 'variant' parameter existed in GET.
1932 * /w/index.php?title=Main_page should always be served; but
1933 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1935 function addAcceptLanguage() {
1936 $title = $this->getTitle();
1937 if ( !$title instanceof Title
) {
1941 $lang = $title->getPageLanguage();
1942 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1943 $variants = $lang->getVariants();
1944 $aloption = array();
1945 foreach ( $variants as $variant ) {
1946 if ( $variant === $lang->getCode() ) {
1949 $aloption[] = 'string-contains=' . $variant;
1951 // IE and some other browsers use BCP 47 standards in
1952 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1953 // We should handle these too.
1954 $variantBCP47 = wfBCP47( $variant );
1955 if ( $variantBCP47 !== $variant ) {
1956 $aloption[] = 'string-contains=' . $variantBCP47;
1960 $this->addVaryHeader( 'Accept-Language', $aloption );
1965 * Set a flag which will cause an X-Frame-Options header appropriate for
1966 * edit pages to be sent. The header value is controlled by
1967 * $wgEditPageFrameOptions.
1969 * This is the default for special pages. If you display a CSRF-protected
1970 * form on an ordinary view page, then you need to call this function.
1972 * @param bool $enable
1974 public function preventClickjacking( $enable = true ) {
1975 $this->mPreventClickjacking
= $enable;
1979 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1980 * This can be called from pages which do not contain any CSRF-protected
1983 public function allowClickjacking() {
1984 $this->mPreventClickjacking
= false;
1988 * Get the prevent-clickjacking flag
1993 public function getPreventClickjacking() {
1994 return $this->mPreventClickjacking
;
1998 * Get the X-Frame-Options header value (without the name part), or false
1999 * if there isn't one. This is used by Skin to determine whether to enable
2000 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2004 public function getFrameOptions() {
2005 $config = $this->getConfig();
2006 if ( $config->get( 'BreakFrames' ) ) {
2008 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2009 return $config->get( 'EditPageFrameOptions' );
2015 * Send cache control HTTP headers
2017 public function sendCacheControl() {
2018 $response = $this->getRequest()->response();
2019 $config = $this->getConfig();
2020 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2021 $response->header( "ETag: $this->mETag" );
2024 $this->addVaryHeader( 'Cookie' );
2025 $this->addAcceptLanguage();
2027 # don't serve compressed data to clients who can't handle it
2028 # maintain different caches for logged-in users and non-logged in ones
2029 $response->header( $this->getVaryHeader() );
2031 if ( $config->get( 'UseXVO' ) ) {
2032 # Add an X-Vary-Options header for Squid with Wikimedia patches
2033 $response->header( $this->getXVO() );
2036 if ( $this->mEnableClientCache
) {
2038 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2039 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2041 if ( $config->get( 'UseESI' ) ) {
2042 # We'll purge the proxy cache explicitly, but require end user agents
2043 # to revalidate against the proxy on each visit.
2044 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2045 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2046 # start with a shorter timeout for initial testing
2047 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2048 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2049 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2050 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2052 # We'll purge the proxy cache for anons explicitly, but require end user agents
2053 # to revalidate against the proxy on each visit.
2054 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2055 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2056 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2057 # start with a shorter timeout for initial testing
2058 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2059 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2060 . ', must-revalidate, max-age=0' );
2063 # We do want clients to cache if they can, but they *must* check for updates
2064 # on revisiting the page.
2065 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2066 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2067 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2069 if ( $this->mLastModified
) {
2070 $response->header( "Last-Modified: {$this->mLastModified}" );
2073 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2075 # In general, the absence of a last modified header should be enough to prevent
2076 # the client from using its cache. We send a few other things just to make sure.
2077 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2078 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2079 $response->header( 'Pragma: no-cache' );
2084 * Finally, all the text has been munged and accumulated into
2085 * the object, let's actually output it:
2087 public function output() {
2088 global $wgLanguageCode;
2090 if ( $this->mDoNothing
) {
2094 wfProfileIn( __METHOD__
);
2096 $response = $this->getRequest()->response();
2097 $config = $this->getConfig();
2099 if ( $this->mRedirect
!= '' ) {
2100 # Standards require redirect URLs to be absolute
2101 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2103 $redirect = $this->mRedirect
;
2104 $code = $this->mRedirectCode
;
2106 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2107 if ( $code == '301' ||
$code == '303' ) {
2108 if ( !$config->get( 'DebugRedirects' ) ) {
2109 $message = HttpStatus
::getMessage( $code );
2110 $response->header( "HTTP/1.1 $code $message" );
2112 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2114 if ( $config->get( 'VaryOnXFP' ) ) {
2115 $this->addVaryHeader( 'X-Forwarded-Proto' );
2117 $this->sendCacheControl();
2119 $response->header( "Content-Type: text/html; charset=utf-8" );
2120 if ( $config->get( 'DebugRedirects' ) ) {
2121 $url = htmlspecialchars( $redirect );
2122 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2123 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2124 print "</body>\n</html>\n";
2126 $response->header( 'Location: ' . $redirect );
2130 wfProfileOut( __METHOD__
);
2132 } elseif ( $this->mStatusCode
) {
2133 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2135 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2139 # Buffer output; final headers may depend on later processing
2142 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2143 $response->header( 'Content-language: ' . $wgLanguageCode );
2145 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2146 // jQuery etc. can work correctly.
2147 $response->header( 'X-UA-Compatible: IE=Edge' );
2149 // Prevent framing, if requested
2150 $frameOptions = $this->getFrameOptions();
2151 if ( $frameOptions ) {
2152 $response->header( "X-Frame-Options: $frameOptions" );
2155 if ( $this->mArticleBodyOnly
) {
2156 echo $this->mBodytext
;
2159 $sk = $this->getSkin();
2160 // add skin specific modules
2161 $modules = $sk->getDefaultModules();
2163 // enforce various default modules for all skins
2164 $coreModules = array(
2165 // keep this list as small as possible
2166 'mediawiki.page.startup',
2170 // Support for high-density display images if enabled
2171 if ( $config->get( 'ResponsiveImages' ) ) {
2172 $coreModules[] = 'mediawiki.hidpi';
2175 $this->addModules( $coreModules );
2176 foreach ( $modules as $group ) {
2177 $this->addModules( $group );
2179 MWDebug
::addModules( $this );
2181 // Hook that allows last minute changes to the output page, e.g.
2182 // adding of CSS or Javascript by extensions.
2183 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2185 wfProfileIn( 'Output-skin' );
2187 wfProfileOut( 'Output-skin' );
2190 // This hook allows last minute changes to final overall output by modifying output buffer
2191 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2193 $this->sendCacheControl();
2197 wfProfileOut( __METHOD__
);
2201 * Actually output something with print.
2203 * @param string $ins The string to output
2204 * @deprecated since 1.22 Use echo yourself.
2206 public function out( $ins ) {
2207 wfDeprecated( __METHOD__
, '1.22' );
2212 * Produce a "user is blocked" page.
2213 * @deprecated since 1.18
2215 function blockedPage() {
2216 throw new UserBlockedError( $this->getUser()->mBlock
);
2220 * Prepare this object to display an error page; disable caching and
2221 * indexing, clear the current text and redirect, set the page's title
2222 * and optionally an custom HTML title (content of the "<title>" tag).
2224 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2225 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2226 * optional, if not passed the "<title>" attribute will be
2227 * based on $pageTitle
2229 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2230 $this->setPageTitle( $pageTitle );
2231 if ( $htmlTitle !== false ) {
2232 $this->setHTMLTitle( $htmlTitle );
2234 $this->setRobotPolicy( 'noindex,nofollow' );
2235 $this->setArticleRelated( false );
2236 $this->enableClientCache( false );
2237 $this->mRedirect
= '';
2238 $this->clearSubtitle();
2243 * Output a standard error page
2245 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2246 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2247 * showErrorPage( 'titlemsg', $messageObject );
2248 * showErrorPage( $titleMessageObject, $messageObject );
2250 * @param string|Message $title Message key (string) for page title, or a Message object
2251 * @param string|Message $msg Message key (string) for page text, or a Message object
2252 * @param array $params Message parameters; ignored if $msg is a Message object
2254 public function showErrorPage( $title, $msg, $params = array() ) {
2255 if ( !$title instanceof Message
) {
2256 $title = $this->msg( $title );
2259 $this->prepareErrorPage( $title );
2261 if ( $msg instanceof Message
) {
2262 if ( $params !== array() ) {
2263 trigger_error( 'Argument ignored: $params. The message parameters argument '
2264 . 'is discarded when the $msg argument is a Message object instead of '
2265 . 'a string.', E_USER_NOTICE
);
2267 $this->addHTML( $msg->parseAsBlock() );
2269 $this->addWikiMsgArray( $msg, $params );
2272 $this->returnToMain();
2276 * Output a standard permission error page
2278 * @param array $errors Error message keys
2279 * @param string $action Action that was denied or null if unknown
2281 public function showPermissionsErrorPage( array $errors, $action = null ) {
2282 // For some action (read, edit, create and upload), display a "login to do this action"
2283 // error if all of the following conditions are met:
2284 // 1. the user is not logged in
2285 // 2. the only error is insufficient permissions (i.e. no block or something else)
2286 // 3. the error can be avoided simply by logging in
2287 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2288 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2289 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2290 && ( User
::groupHasPermission( 'user', $action )
2291 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2293 $displayReturnto = null;
2295 # Due to bug 32276, if a user does not have read permissions,
2296 # $this->getTitle() will just give Special:Badtitle, which is
2297 # not especially useful as a returnto parameter. Use the title
2298 # from the request instead, if there was one.
2299 $request = $this->getRequest();
2300 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2301 if ( $action == 'edit' ) {
2302 $msg = 'whitelistedittext';
2303 $displayReturnto = $returnto;
2304 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2305 $msg = 'nocreatetext';
2306 } elseif ( $action == 'upload' ) {
2307 $msg = 'uploadnologintext';
2309 $msg = 'loginreqpagetext';
2310 $displayReturnto = Title
::newMainPage();
2316 $query['returnto'] = $returnto->getPrefixedText();
2318 if ( !$request->wasPosted() ) {
2319 $returntoquery = $request->getValues();
2320 unset( $returntoquery['title'] );
2321 unset( $returntoquery['returnto'] );
2322 unset( $returntoquery['returntoquery'] );
2323 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2326 $loginLink = Linker
::linkKnown(
2327 SpecialPage
::getTitleFor( 'Userlogin' ),
2328 $this->msg( 'loginreqlink' )->escaped(),
2333 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2334 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2336 # Don't return to a page the user can't read otherwise
2337 # we'll end up in a pointless loop
2338 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2339 $this->returnToMain( null, $displayReturnto );
2342 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2343 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2348 * Display an error page indicating that a given version of MediaWiki is
2349 * required to use it
2351 * @param mixed $version The version of MediaWiki needed to use the page
2353 public function versionRequired( $version ) {
2354 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2356 $this->addWikiMsg( 'versionrequiredtext', $version );
2357 $this->returnToMain();
2361 * Display an error page noting that a given permission bit is required.
2362 * @deprecated since 1.18, just throw the exception directly
2363 * @param string $permission Key required
2364 * @throws PermissionsError
2366 public function permissionRequired( $permission ) {
2367 throw new PermissionsError( $permission );
2371 * Produce the stock "please login to use the wiki" page
2373 * @deprecated since 1.19; throw the exception directly
2375 public function loginToUse() {
2376 throw new PermissionsError( 'read' );
2380 * Format a list of error messages
2382 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2383 * @param string $action Action that was denied or null if unknown
2384 * @return string The wikitext error-messages, formatted into a list.
2386 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2387 if ( $action == null ) {
2388 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2390 $action_desc = $this->msg( "action-$action" )->plain();
2392 'permissionserrorstext-withaction',
2395 )->plain() . "\n\n";
2398 if ( count( $errors ) > 1 ) {
2399 $text .= '<ul class="permissions-errors">' . "\n";
2401 foreach ( $errors as $error ) {
2403 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2408 $text .= "<div class=\"permissions-errors\">\n" .
2409 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2417 * Display a page stating that the Wiki is in read-only mode.
2418 * Should only be called after wfReadOnly() has returned true.
2420 * Historically, this function was used to show the source of the page that the user
2421 * was trying to edit and _also_ permissions error messages. The relevant code was
2422 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2424 * @deprecated since 1.25; throw the exception directly
2425 * @throws ReadOnlyError
2427 public function readOnlyPage() {
2428 if ( func_num_args() > 0 ) {
2429 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2432 throw new ReadOnlyError
;
2436 * Turn off regular page output and return an error response
2437 * for when rate limiting has triggered.
2439 public function rateLimited() {
2440 throw new ThrottledError
;
2444 * Show a warning about slave lag
2446 * If the lag is higher than $wgSlaveLagCritical seconds,
2447 * then the warning is a bit more obvious. If the lag is
2448 * lower than $wgSlaveLagWarning, then no warning is shown.
2450 * @param int $lag Slave lag
2452 public function showLagWarning( $lag ) {
2453 $config = $this->getConfig();
2454 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2455 $message = $lag < $config->get( 'SlaveLagCritical' )
2458 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2459 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2463 public function showFatalError( $message ) {
2464 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2466 $this->addHTML( $message );
2469 public function showUnexpectedValueError( $name, $val ) {
2470 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2473 public function showFileCopyError( $old, $new ) {
2474 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2477 public function showFileRenameError( $old, $new ) {
2478 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2481 public function showFileDeleteError( $name ) {
2482 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2485 public function showFileNotFoundError( $name ) {
2486 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2490 * Add a "return to" link pointing to a specified title
2492 * @param Title $title Title to link
2493 * @param array $query Query string parameters
2494 * @param string $text Text of the link (input is not escaped)
2495 * @param array $options Options array to pass to Linker
2497 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2498 $link = $this->msg( 'returnto' )->rawParams(
2499 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2500 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2504 * Add a "return to" link pointing to a specified title,
2505 * or the title indicated in the request, or else the main page
2507 * @param mixed $unused
2508 * @param Title|string $returnto Title or String to return to
2509 * @param string $returntoquery Query string for the return to link
2511 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2512 if ( $returnto == null ) {
2513 $returnto = $this->getRequest()->getText( 'returnto' );
2516 if ( $returntoquery == null ) {
2517 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2520 if ( $returnto === '' ) {
2521 $returnto = Title
::newMainPage();
2524 if ( is_object( $returnto ) ) {
2525 $titleObj = $returnto;
2527 $titleObj = Title
::newFromText( $returnto );
2529 if ( !is_object( $titleObj ) ) {
2530 $titleObj = Title
::newMainPage();
2533 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2537 * @param Skin $sk The given Skin
2538 * @param bool $includeStyle Unused
2539 * @return string The doctype, opening "<html>", and head element.
2541 public function headElement( Skin
$sk, $includeStyle = true ) {
2544 $section = new ProfileSection( __METHOD__
);
2546 $userdir = $this->getLanguage()->getDir();
2547 $sitedir = $wgContLang->getDir();
2549 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2551 if ( $this->getHTMLTitle() == '' ) {
2552 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2555 $openHead = Html
::openElement( 'head' );
2557 # Don't bother with the newline if $head == ''
2558 $ret .= "$openHead\n";
2561 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2562 // Add <meta charset="UTF-8">
2563 // This should be before <title> since it defines the charset used by
2564 // text including the text inside <title>.
2565 // The spec recommends defining XHTML5's charset using the XML declaration
2567 // Our XML declaration is output by Html::htmlHeader.
2568 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2569 // http://www.whatwg.org/html/semantics.html#charset
2570 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2573 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2575 foreach ( $this->getHeadLinksArray() as $item ) {
2576 $ret .= $item . "\n";
2579 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2580 $ret .= $this->buildCssLinks();
2582 $ret .= $this->getHeadScripts() . "\n";
2584 foreach ( $this->mHeadItems
as $item ) {
2585 $ret .= $item . "\n";
2588 $closeHead = Html
::closeElement( 'head' );
2590 $ret .= "$closeHead\n";
2593 $bodyClasses = array();
2594 $bodyClasses[] = 'mediawiki';
2596 # Classes for LTR/RTL directionality support
2597 $bodyClasses[] = $userdir;
2598 $bodyClasses[] = "sitedir-$sitedir";
2600 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2601 # A <body> class is probably not the best way to do this . . .
2602 $bodyClasses[] = 'capitalize-all-nouns';
2605 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2606 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2608 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2610 $bodyAttrs = array();
2611 // While the implode() is not strictly needed, it's used for backwards compatibility
2612 // (this used to be built as a string and hooks likely still expect that).
2613 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2615 // Allow skins and extensions to add body attributes they need
2616 $sk->addToBodyAttributes( $this, $bodyAttrs );
2617 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2619 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2625 * Get a ResourceLoader object associated with this OutputPage
2627 * @return ResourceLoader
2629 public function getResourceLoader() {
2630 if ( is_null( $this->mResourceLoader
) ) {
2631 $this->mResourceLoader
= new ResourceLoader( $this->getConfig() );
2633 return $this->mResourceLoader
;
2638 * @param array|string $modules One or more module names
2639 * @param string $only ResourceLoaderModule TYPE_ class constant
2640 * @param bool $useESI
2641 * @param array $extraQuery Array with extra query parameters to add to each
2642 * request. array( param => value ).
2643 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2644 * call rather than a "<script src='...'>" tag.
2645 * @return string The html "<script>", "<link>" and "<style>" tags
2647 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2648 array $extraQuery = array(), $loadCall = false
2650 $modules = (array)$modules;
2654 'states' => array(),
2657 if ( !count( $modules ) ) {
2661 if ( count( $modules ) > 1 ) {
2662 // Remove duplicate module requests
2663 $modules = array_unique( $modules );
2664 // Sort module names so requests are more uniform
2667 if ( ResourceLoader
::inDebugMode() ) {
2668 // Recursively call us for every item
2669 foreach ( $modules as $name ) {
2670 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2671 $links['html'] .= $link['html'];
2672 $links['states'] +
= $link['states'];
2678 if ( !is_null( $this->mTarget
) ) {
2679 $extraQuery['target'] = $this->mTarget
;
2682 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2683 $sortedModules = array();
2684 $resourceLoader = $this->getResourceLoader();
2685 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2686 foreach ( $modules as $name ) {
2687 $module = $resourceLoader->getModule( $name );
2688 # Check that we're allowed to include this module on this page
2690 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2691 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2692 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2693 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2694 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2695 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2696 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2701 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2704 foreach ( $sortedModules as $source => $groups ) {
2705 foreach ( $groups as $group => $grpModules ) {
2706 // Special handling for user-specific groups
2708 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2709 $user = $this->getUser()->getName();
2712 // Create a fake request based on the one we are about to make so modules return
2713 // correct timestamp and emptiness data
2714 $query = ResourceLoader
::makeLoaderQuery(
2715 array(), // modules; not determined yet
2716 $this->getLanguage()->getCode(),
2717 $this->getSkin()->getSkinName(),
2719 null, // version; not determined yet
2720 ResourceLoader
::inDebugMode(),
2721 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2722 $this->isPrintable(),
2723 $this->getRequest()->getBool( 'handheld' ),
2726 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2728 // Extract modules that know they're empty and see if we have one or more
2731 foreach ( $grpModules as $key => $module ) {
2732 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2733 // If we're only getting the styles, we don't need to do anything for empty modules.
2734 if ( $module->isKnownEmpty( $context ) ) {
2735 unset( $grpModules[$key] );
2736 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2737 $links['states'][$key] = 'ready';
2741 $isRaw |
= $module->isRaw();
2744 // If there are no non-empty modules, skip this group
2745 if ( count( $grpModules ) === 0 ) {
2749 // Inline private modules. These can't be loaded through load.php for security
2750 // reasons, see bug 34907. Note that these modules should be loaded from
2751 // getHeadScripts() before the first loader call. Otherwise other modules can't
2752 // properly use them as dependencies (bug 30914)
2753 if ( $group === 'private' ) {
2754 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2755 $links['html'] .= Html
::inlineStyle(
2756 $resourceLoader->makeModuleResponse( $context, $grpModules )
2759 $links['html'] .= Html
::inlineScript(
2760 ResourceLoader
::makeLoaderConditionalScript(
2761 $resourceLoader->makeModuleResponse( $context, $grpModules )
2765 $links['html'] .= "\n";
2769 // Special handling for the user group; because users might change their stuff
2770 // on-wiki like user pages, or user preferences; we need to find the highest
2771 // timestamp of these user-changeable modules so we can ensure cache misses on change
2772 // This should NOT be done for the site group (bug 27564) because anons get that too
2773 // and we shouldn't be putting timestamps in Squid-cached HTML
2775 if ( $group === 'user' ) {
2776 // Get the maximum timestamp
2778 foreach ( $grpModules as $module ) {
2779 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2781 // Add a version parameter so cache will break when things change
2782 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2785 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2786 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2787 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2789 if ( $useESI && $resourceLoaderUseESI ) {
2790 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2791 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2792 $link = Html
::inlineStyle( $esi );
2794 $link = Html
::inlineScript( $esi );
2797 // Automatically select style/script elements
2798 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2799 $link = Html
::linkedStyle( $url );
2800 } elseif ( $loadCall ) {
2801 $link = Html
::inlineScript(
2802 ResourceLoader
::makeLoaderConditionalScript(
2803 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2807 $link = Html
::linkedScript( $url );
2808 if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
2809 // Wrap only=script requests in a conditional as browsers not supported
2810 // by the startup module would unconditionally execute this module.
2811 // Otherwise users will get "ReferenceError: mw is undefined" or
2812 // "jQuery is undefined" from e.g. a "site" module.
2813 $link = Html
::inlineScript(
2814 ResourceLoader
::makeLoaderConditionalScript(
2815 Xml
::encodeJsCall( 'document.write', array( $link ) )
2820 // For modules requested directly in the html via <link> or <script>,
2821 // tell mw.loader they are being loading to prevent duplicate requests.
2822 foreach ( $grpModules as $key => $module ) {
2823 // Don't output state=loading for the startup module..
2824 if ( $key !== 'startup' ) {
2825 $links['states'][$key] = 'loading';
2831 if ( $group == 'noscript' ) {
2832 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2834 $links['html'] .= $link . "\n";
2843 * Build html output from an array of links from makeResourceLoaderLink.
2844 * @param array $links
2845 * @return string HTML
2847 protected static function getHtmlFromLoaderLinks( array $links ) {
2850 foreach ( $links as $link ) {
2851 if ( !is_array( $link ) ) {
2854 $html .= $link['html'];
2855 $states +
= $link['states'];
2859 if ( count( $states ) ) {
2860 $html = Html
::inlineScript(
2861 ResourceLoader
::makeLoaderConditionalScript(
2862 ResourceLoader
::makeLoaderStateScript( $states )
2871 * JS stuff to put in the "<head>". This is the startup module, config
2872 * vars and modules marked with position 'top'
2874 * @return string HTML fragment
2876 function getHeadScripts() {
2877 // Startup - this will immediately load jquery and mediawiki modules
2879 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2881 // Load config before anything else
2882 $links[] = Html
::inlineScript(
2883 ResourceLoader
::makeLoaderConditionalScript(
2884 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2888 // Load embeddable private modules before any loader links
2889 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2890 // in mw.loader.implement() calls and deferred until mw.user is available
2891 $embedScripts = array( 'user.options', 'user.tokens' );
2892 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2894 // Scripts and messages "only" requests marked for top inclusion
2895 // Messages should go first
2896 $links[] = $this->makeResourceLoaderLink(
2897 $this->getModuleMessages( true, 'top' ),
2898 ResourceLoaderModule
::TYPE_MESSAGES
2900 $links[] = $this->makeResourceLoaderLink(
2901 $this->getModuleScripts( true, 'top' ),
2902 ResourceLoaderModule
::TYPE_SCRIPTS
2905 // Modules requests - let the client calculate dependencies and batch requests as it likes
2906 // Only load modules that have marked themselves for loading at the top
2907 $modules = $this->getModules( true, 'top' );
2909 $links[] = Html
::inlineScript(
2910 ResourceLoader
::makeLoaderConditionalScript(
2911 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2916 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2917 $links[] = $this->getScriptsForBottomQueue( true );
2920 return self
::getHtmlFromLoaderLinks( $links );
2924 * JS stuff to put at the 'bottom', which can either be the bottom of the
2925 * "<body>" or the bottom of the "<head>" depending on
2926 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2927 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2930 * @param bool $inHead If true, this HTML goes into the "<head>",
2931 * if false it goes into the "<body>".
2934 function getScriptsForBottomQueue( $inHead ) {
2935 // Scripts and messages "only" requests marked for bottom inclusion
2936 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2937 // Messages should go first
2939 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2940 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2941 /* $loadCall = */ $inHead
2943 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2944 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2945 /* $loadCall = */ $inHead
2948 // Modules requests - let the client calculate dependencies and batch requests as it likes
2949 // Only load modules that have marked themselves for loading at the bottom
2950 $modules = $this->getModules( true, 'bottom' );
2952 $links[] = Html
::inlineScript(
2953 ResourceLoader
::makeLoaderConditionalScript(
2954 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2960 $links[] = "\n" . $this->mScripts
;
2962 // Add site JS if enabled
2963 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2964 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2967 // Add user JS if enabled
2968 if ( $this->getConfig()->get( 'AllowUserJs' )
2969 && $this->getUser()->isLoggedIn()
2970 && $this->getTitle()
2971 && $this->getTitle()->isJsSubpage()
2972 && $this->userCanPreview()
2974 # XXX: additional security check/prompt?
2975 // We're on a preview of a JS subpage
2976 // Exclude this page from the user module in case it's in there (bug 26283)
2977 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2978 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2980 // Load the previewed JS
2981 $links[] = Html
::inlineScript( "\n"
2982 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2984 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2985 // asynchronously and may arrive *after* the inline script here. So the previewed code
2986 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2988 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2989 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2990 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2994 // Group JS is only enabled if site JS is enabled.
2995 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2996 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2999 return self
::getHtmlFromLoaderLinks( $links );
3003 * JS stuff to put at the bottom of the "<body>"
3006 function getBottomScripts() {
3007 // Optimise jQuery ready event cross-browser.
3008 // This also enforces $.isReady to be true at </body> which fixes the
3009 // mw.loader bug in Firefox with using document.write between </body>
3010 // and the DOMContentReady event (bug 47457).
3011 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3013 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3014 $html .= $this->getScriptsForBottomQueue( false );
3021 * Get the javascript config vars to include on this page
3023 * @return array Array of javascript config vars
3026 public function getJsConfigVars() {
3027 return $this->mJsConfigVars
;
3031 * Add one or more variables to be set in mw.config in JavaScript
3033 * @param string|array $keys Key or array of key/value pairs
3034 * @param mixed $value [optional] Value of the configuration variable
3036 public function addJsConfigVars( $keys, $value = null ) {
3037 if ( is_array( $keys ) ) {
3038 foreach ( $keys as $key => $value ) {
3039 $this->mJsConfigVars
[$key] = $value;
3044 $this->mJsConfigVars
[$keys] = $value;
3048 * Get an array containing the variables to be set in mw.config in JavaScript.
3050 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3051 * - in other words, page-independent/site-wide variables (without state).
3052 * You will only be adding bloat to the html page and causing page caches to
3053 * have to be purged on configuration changes.
3056 private function getJSVars() {
3061 $canonicalSpecialPageName = false; # bug 21115
3063 $title = $this->getTitle();
3064 $ns = $title->getNamespace();
3065 $canonicalNamespace = MWNamespace
::exists( $ns )
3066 ? MWNamespace
::getCanonicalName( $ns )
3067 : $title->getNsText();
3069 $sk = $this->getSkin();
3070 // Get the relevant title so that AJAX features can use the correct page name
3071 // when making API requests from certain special pages (bug 34972).
3072 $relevantTitle = $sk->getRelevantTitle();
3073 $relevantUser = $sk->getRelevantUser();
3075 if ( $ns == NS_SPECIAL
) {
3076 list( $canonicalSpecialPageName, /*...*/ ) =
3077 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3078 } elseif ( $this->canUseWikiPage() ) {
3079 $wikiPage = $this->getWikiPage();
3080 $curRevisionId = $wikiPage->getLatest();
3081 $articleId = $wikiPage->getId();
3084 $lang = $title->getPageLanguage();
3086 // Pre-process information
3087 $separatorTransTable = $lang->separatorTransformTable();
3088 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3089 $compactSeparatorTransTable = array(
3090 implode( "\t", array_keys( $separatorTransTable ) ),
3091 implode( "\t", $separatorTransTable ),
3093 $digitTransTable = $lang->digitTransformTable();
3094 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3095 $compactDigitTransTable = array(
3096 implode( "\t", array_keys( $digitTransTable ) ),
3097 implode( "\t", $digitTransTable ),
3100 $user = $this->getUser();
3103 'wgCanonicalNamespace' => $canonicalNamespace,
3104 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3105 'wgNamespaceNumber' => $title->getNamespace(),
3106 'wgPageName' => $title->getPrefixedDBkey(),
3107 'wgTitle' => $title->getText(),
3108 'wgCurRevisionId' => $curRevisionId,
3109 'wgRevisionId' => (int)$this->getRevisionId(),
3110 'wgArticleId' => $articleId,
3111 'wgIsArticle' => $this->isArticle(),
3112 'wgIsRedirect' => $title->isRedirect(),
3113 'wgAction' => Action
::getActionName( $this->getContext() ),
3114 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3115 'wgUserGroups' => $user->getEffectiveGroups(),
3116 'wgCategories' => $this->getCategories(),
3117 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3118 'wgPageContentLanguage' => $lang->getCode(),
3119 'wgPageContentModel' => $title->getContentModel(),
3120 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3121 'wgDigitTransformTable' => $compactDigitTransTable,
3122 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3123 'wgMonthNames' => $lang->getMonthNamesArray(),
3124 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3125 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3128 if ( $user->isLoggedIn() ) {
3129 $vars['wgUserId'] = $user->getId();
3130 $vars['wgUserEditCount'] = $user->getEditCount();
3131 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3132 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3133 // Get the revision ID of the oldest new message on the user's talk
3134 // page. This can be used for constructing new message alerts on
3136 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3139 if ( $wgContLang->hasVariants() ) {
3140 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3142 // Same test as SkinTemplate
3143 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3144 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3146 foreach ( $title->getRestrictionTypes() as $type ) {
3147 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3150 if ( $title->isMainPage() ) {
3151 $vars['wgIsMainPage'] = true;
3154 if ( $this->mRedirectedFrom
) {
3155 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3158 if ( $relevantUser ) {
3159 $vars['wgRelevantUserName'] = $relevantUser->getName();
3162 // Allow extensions to add their custom variables to the mw.config map.
3163 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3164 // page-dependant but site-wide (without state).
3165 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3166 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3168 // Merge in variables from addJsConfigVars last
3169 return array_merge( $vars, $this->getJsConfigVars() );
3173 * To make it harder for someone to slip a user a fake
3174 * user-JavaScript or user-CSS preview, a random token
3175 * is associated with the login session. If it's not
3176 * passed back with the preview request, we won't render
3181 public function userCanPreview() {
3182 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3183 ||
!$this->getRequest()->wasPosted()
3184 ||
!$this->getUser()->matchEditToken(
3185 $this->getRequest()->getVal( 'wpEditToken' ) )
3189 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3193 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3197 * @return array Array in format "link name or number => 'link html'".
3199 public function getHeadLinksArray() {
3203 $config = $this->getConfig();
3205 $canonicalUrl = $this->mCanonicalUrl
;
3207 $tags['meta-generator'] = Html
::element( 'meta', array(
3208 'name' => 'generator',
3209 'content' => "MediaWiki $wgVersion",
3212 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3213 if ( $p !== 'index,follow' ) {
3214 // http://www.robotstxt.org/wc/meta-user.html
3215 // Only show if it's different from the default robots policy
3216 $tags['meta-robots'] = Html
::element( 'meta', array(
3222 foreach ( $this->mMetatags
as $tag ) {
3223 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3225 $tag[0] = substr( $tag[0], 5 );
3229 $tagName = "meta-{$tag[0]}";
3230 if ( isset( $tags[$tagName] ) ) {
3231 $tagName .= $tag[1];
3233 $tags[$tagName] = Html
::element( 'meta',
3236 'content' => $tag[1]
3241 foreach ( $this->mLinktags
as $tag ) {
3242 $tags[] = Html
::element( 'link', $tag );
3245 # Universal edit button
3246 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3247 $user = $this->getUser();
3248 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3249 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3250 // Original UniversalEditButton
3251 $msg = $this->msg( 'edit' )->text();
3252 $tags['universal-edit-button'] = Html
::element( 'link', array(
3253 'rel' => 'alternate',
3254 'type' => 'application/x-wiki',
3256 'href' => $this->getTitle()->getEditURL(),
3258 // Alternate edit link
3259 $tags['alternative-edit'] = Html
::element( 'link', array(
3262 'href' => $this->getTitle()->getEditURL(),
3267 # Generally the order of the favicon and apple-touch-icon links
3268 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3269 # uses whichever one appears later in the HTML source. Make sure
3270 # apple-touch-icon is specified first to avoid this.
3271 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3272 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3273 'rel' => 'apple-touch-icon',
3274 'href' => $config->get( 'AppleTouchIcon' )
3278 if ( $config->get( 'Favicon' ) !== false ) {
3279 $tags['favicon'] = Html
::element( 'link', array(
3280 'rel' => 'shortcut icon',
3281 'href' => $config->get( 'Favicon' )
3285 # OpenSearch description link
3286 $tags['opensearch'] = Html
::element( 'link', array(
3288 'type' => 'application/opensearchdescription+xml',
3289 'href' => wfScript( 'opensearch_desc' ),
3290 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3293 if ( $config->get( 'EnableAPI' ) ) {
3294 # Real Simple Discovery link, provides auto-discovery information
3295 # for the MediaWiki API (and potentially additional custom API
3296 # support such as WordPress or Twitter-compatible APIs for a
3297 # blogging extension, etc)
3298 $tags['rsd'] = Html
::element( 'link', array(
3300 'type' => 'application/rsd+xml',
3301 // Output a protocol-relative URL here if $wgServer is protocol-relative
3302 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3303 'href' => wfExpandUrl( wfAppendQuery(
3305 array( 'action' => 'rsd' ) ),
3312 if ( !$config->get( 'DisableLangConversion' ) ) {
3313 $lang = $this->getTitle()->getPageLanguage();
3314 if ( $lang->hasVariants() ) {
3315 $variants = $lang->getVariants();
3316 foreach ( $variants as $_v ) {
3317 $tags["variant-$_v"] = Html
::element( 'link', array(
3318 'rel' => 'alternate',
3319 'hreflang' => wfBCP47( $_v ),
3320 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3324 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3325 $tags["variant-x-default"] = Html
::element( 'link', array(
3326 'rel' => 'alternate',
3327 'hreflang' => 'x-default',
3328 'href' => $this->getTitle()->getLocalURL() ) );
3333 if ( $config->get( 'RightsPage' ) ) {
3334 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3337 $copyright = $copy->getLocalURL();
3341 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3342 $copyright = $config->get( 'RightsUrl' );
3346 $tags['copyright'] = Html
::element( 'link', array(
3347 'rel' => 'copyright',
3348 'href' => $copyright )
3353 if ( $config->get( 'Feed' ) ) {
3354 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3355 # Use the page name for the title. In principle, this could
3356 # lead to issues with having the same name for different feeds
3357 # corresponding to the same page, but we can't avoid that at
3360 $tags[] = $this->feedLink(
3363 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3364 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3368 # Recent changes feed should appear on every page (except recentchanges,
3369 # that would be redundant). Put it after the per-page feed to avoid
3370 # changing existing behavior. It's still available, probably via a
3371 # menu in your browser. Some sites might have a different feed they'd
3372 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3373 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3374 # If so, use it instead.
3375 $sitename = $config->get( 'Sitename' );
3376 if ( $config->get( 'OverrideSiteFeed' ) ) {
3377 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3378 // Note, this->feedLink escapes the url.
3379 $tags[] = $this->feedLink(
3382 $this->msg( "site-{$type}-feed", $sitename )->text()
3385 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3386 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3387 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3388 $tags[] = $this->feedLink(
3390 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3391 # For grep: 'site-rss-feed', 'site-atom-feed'
3392 $this->msg( "site-{$format}-feed", $sitename )->text()
3399 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3400 if ( $canonicalUrl !== false ) {
3401 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3403 $reqUrl = $this->getRequest()->getRequestURL();
3404 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3407 if ( $canonicalUrl !== false ) {
3408 $tags[] = Html
::element( 'link', array(
3409 'rel' => 'canonical',
3410 'href' => $canonicalUrl
3418 * @return string HTML tag links to be put in the header.
3419 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3420 * OutputPage::getHeadLinksArray directly.
3422 public function getHeadLinks() {
3423 wfDeprecated( __METHOD__
, '1.24' );
3424 return implode( "\n", $this->getHeadLinksArray() );
3428 * Generate a "<link rel/>" for a feed.
3430 * @param string $type Feed type
3431 * @param string $url URL to the feed
3432 * @param string $text Value of the "title" attribute
3433 * @return string HTML fragment
3435 private function feedLink( $type, $url, $text ) {
3436 return Html
::element( 'link', array(
3437 'rel' => 'alternate',
3438 'type' => "application/$type+xml",
3445 * Add a local or specified stylesheet, with the given media options.
3446 * Meant primarily for internal use...
3448 * @param string $style URL to the file
3449 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3450 * @param string $condition For IE conditional comments, specifying an IE version
3451 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3453 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3455 // Even though we expect the media type to be lowercase, but here we
3456 // force it to lowercase to be safe.
3458 $options['media'] = $media;
3461 $options['condition'] = $condition;
3464 $options['dir'] = $dir;
3466 $this->styles
[$style] = $options;
3470 * Adds inline CSS styles
3471 * @param mixed $style_css Inline CSS
3472 * @param string $flip Set to 'flip' to flip the CSS if needed
3474 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3475 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3476 # If wanted, and the interface is right-to-left, flip the CSS
3477 $style_css = CSSJanus
::transform( $style_css, true, false );
3479 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3483 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3484 * These will be applied to various media & IE conditionals.
3488 public function buildCssLinks() {
3491 $this->getSkin()->setupSkinUserCss( $this );
3493 // Add ResourceLoader styles
3494 // Split the styles into these groups
3499 'private' => array(),
3500 'noscript' => array()
3503 $otherTags = ''; // Tags to append after the normal <link> tags
3504 $resourceLoader = $this->getResourceLoader();
3506 $moduleStyles = $this->getModuleStyles();
3508 // Per-site custom styles
3509 $moduleStyles[] = 'site';
3510 $moduleStyles[] = 'noscript';
3511 $moduleStyles[] = 'user.groups';
3513 // Per-user custom styles
3514 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3515 // We're on a preview of a CSS subpage
3516 // Exclude this page from the user module in case it's in there (bug 26283)
3517 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3518 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3520 $otherTags .= $link['html'];
3522 // Load the previewed CSS
3523 // If needed, Janus it first. This is user-supplied CSS, so it's
3524 // assumed to be right for the content language directionality.
3525 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3526 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3527 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3529 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3531 // Load the user styles normally
3532 $moduleStyles[] = 'user';
3535 // Per-user preference styles
3536 $moduleStyles[] = 'user.cssprefs';
3538 foreach ( $moduleStyles as $name ) {
3539 $module = $resourceLoader->getModule( $name );
3543 $group = $module->getGroup();
3544 // Modules in groups different than the ones listed on top (see $styles assignment)
3545 // will be placed in the "other" group
3546 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3549 // We want site, private and user styles to override dynamically added
3550 // styles from modules, but we want dynamically added styles to override
3551 // statically added styles from other modules. So the order has to be
3552 // other, dynamic, site, private, user. Add statically added styles for
3554 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3555 // Add normal styles added through addStyle()/addInlineStyle() here
3556 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3557 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3558 // We use a <meta> tag with a made-up name for this because that's valid HTML
3559 $links[] = Html
::element(
3561 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3564 // Add site, private and user styles
3565 // 'private' at present only contains user.options, so put that before 'user'
3566 // Any future private modules will likely have a similar user-specific character
3567 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3568 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3569 ResourceLoaderModule
::TYPE_STYLES
3573 // Add stuff in $otherTags (previewed user CSS if applicable)
3574 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3580 public function buildCssLinksArray() {
3583 // Add any extension CSS
3584 foreach ( $this->mExtStyles
as $url ) {
3585 $this->addStyle( $url );
3587 $this->mExtStyles
= array();
3589 foreach ( $this->styles
as $file => $options ) {
3590 $link = $this->styleLink( $file, $options );
3592 $links[$file] = $link;
3599 * Generate \<link\> tags for stylesheets
3601 * @param string $style URL to the file
3602 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3603 * @return string HTML fragment
3605 protected function styleLink( $style, array $options ) {
3606 if ( isset( $options['dir'] ) ) {
3607 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3612 if ( isset( $options['media'] ) ) {
3613 $media = self
::transformCssMedia( $options['media'] );
3614 if ( is_null( $media ) ) {
3621 if ( substr( $style, 0, 1 ) == '/' ||
3622 substr( $style, 0, 5 ) == 'http:' ||
3623 substr( $style, 0, 6 ) == 'https:' ) {
3626 $config = $this->getConfig();
3627 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3630 $link = Html
::linkedStyle( $url, $media );
3632 if ( isset( $options['condition'] ) ) {
3633 $condition = htmlspecialchars( $options['condition'] );
3634 $link = "<!--[if $condition]>$link<![endif]-->";
3640 * Transform "media" attribute based on request parameters
3642 * @param string $media Current value of the "media" attribute
3643 * @return string Modified value of the "media" attribute, or null to skip
3646 public static function transformCssMedia( $media ) {
3649 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3650 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3652 // Switch in on-screen display for media testing
3654 'printable' => 'print',
3655 'handheld' => 'handheld',
3657 foreach ( $switches as $switch => $targetMedia ) {
3658 if ( $wgRequest->getBool( $switch ) ) {
3659 if ( $media == $targetMedia ) {
3661 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3662 // This regex will not attempt to understand a comma-separated media_query_list
3664 // Example supported values for $media:
3665 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3666 // Example NOT supported value for $media:
3667 // '3d-glasses, screen, print and resolution > 90dpi'
3669 // If it's a print request, we never want any kind of screen stylesheets
3670 // If it's a handheld request (currently the only other choice with a switch),
3671 // we don't want simple 'screen' but we might want screen queries that
3672 // have a max-width or something, so we'll pass all others on and let the
3673 // client do the query.
3674 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3685 * Add a wikitext-formatted message to the output.
3686 * This is equivalent to:
3688 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3690 public function addWikiMsg( /*...*/ ) {
3691 $args = func_get_args();
3692 $name = array_shift( $args );
3693 $this->addWikiMsgArray( $name, $args );
3697 * Add a wikitext-formatted message to the output.
3698 * Like addWikiMsg() except the parameters are taken as an array
3699 * instead of a variable argument list.
3701 * @param string $name
3702 * @param array $args
3704 public function addWikiMsgArray( $name, $args ) {
3705 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3709 * This function takes a number of message/argument specifications, wraps them in
3710 * some overall structure, and then parses the result and adds it to the output.
3712 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3713 * on. The subsequent arguments may either be strings, in which case they are the
3714 * message names, or arrays, in which case the first element is the message name,
3715 * and subsequent elements are the parameters to that message.
3717 * Don't use this for messages that are not in users interface language.
3721 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3725 * $wgOut->addWikiText( "<div class='error'>\n"
3726 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3728 * The newline after opening div is needed in some wikitext. See bug 19226.
3730 * @param string $wrap
3732 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3733 $msgSpecs = func_get_args();
3734 array_shift( $msgSpecs );
3735 $msgSpecs = array_values( $msgSpecs );
3737 foreach ( $msgSpecs as $n => $spec ) {
3738 if ( is_array( $spec ) ) {
3740 $name = array_shift( $args );
3741 if ( isset( $args['options'] ) ) {
3742 unset( $args['options'] );
3744 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3752 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3754 $this->addWikiText( $s );
3758 * Include jQuery core. Use this to avoid loading it multiple times
3759 * before we get a usable script loader.
3761 * @param array $modules List of jQuery modules which should be loaded
3762 * @return array The list of modules which were not loaded.
3764 * @deprecated since 1.17
3766 public function includeJQuery( array $modules = array() ) {
3771 * Enables/disables TOC, doesn't override __NOTOC__
3775 public function enableTOC( $flag = true ) {
3776 $this->mEnableTOC
= $flag;
3783 public function isTOCEnabled() {
3784 return $this->mEnableTOC
;
3788 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3792 public function enableSectionEditLinks( $flag = true ) {
3793 $this->mEnableSectionEditLinks
= $flag;
3800 public function sectionEditLinksEnabled() {
3801 return $this->mEnableSectionEditLinks
;