638887b2aa31c8eb200fa52287d09329cef771f4
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 /// Should be private. Used with addMeta() which adds "<meta>"
40 var $mMetatags = array();
42 var $mLinktags = array();
43 var $mCanonicalUrl = false;
45 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
46 var $mExtStyles = array();
48 /// Should be private - has getter and setter. Contains the HTML title
51 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
55 * Holds the debug lines that will be output as comments in page source if
56 * $wgDebugComments is enabled. See also $wgShowDebug.
57 * @deprecated since 1.20; use MWDebug class instead.
59 public $mDebugtext = '';
61 /// Should be private. Stores contents of "<title>" tag
64 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
65 var $mIsarticle = false;
68 * Should be private. Has get/set methods properly documented.
69 * Stores "article flag" toggle.
71 var $mIsArticleRelated = true;
74 * Should be private. We have to set isPrintable(). Some pages should
75 * never be printed (ex: redirections).
77 var $mPrintable = false;
80 * Should be private. We have set/get/append methods.
82 * Contains the page subtitle. Special pages usually have some links here.
83 * Don't confuse with site subtitle added by skins.
85 private $mSubtitle = array();
91 * mLastModified and mEtag are used for sending cache control.
92 * The whole caching system should probably be moved into its own class.
94 var $mLastModified = '';
97 * Should be private. No getter but used in sendCacheControl();
98 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
99 * as a unique identifier for the content. It is later used by the client
100 * to compare its cached version with the server version. Client sends
101 * headers If-Match and If-None-Match containing its locally cached ETAG value.
103 * To get more information, you will have to look at HTTP/1.1 protocol which
104 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
108 var $mCategoryLinks = array();
109 var $mCategories = array();
111 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
112 var $mLanguageLinks = array();
115 * Should be private. Used for JavaScript (pre resource loader)
116 * We should split js / css.
117 * mScripts content is inserted as is in "<head>" by Skin. This might
118 * contains either a link to a stylesheet or inline css.
123 * Inline CSS styles. Use addInlineStyle() sparingly
125 var $mInlineStyles = '';
131 * Used by skin template.
132 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
134 var $mPageLinkTitle = '';
136 /// Array of elements in "<head>". Parser might add its own headers!
137 var $mHeadItems = array();
139 // @todo FIXME: Next variables probably comes from the resource loader
140 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
141 var $mResourceLoader;
142 var $mJsConfigVars = array();
144 /** @todo FIXME: Is this still used ?*/
145 var $mInlineMsg = array();
147 var $mTemplateIds = array();
148 var $mImageTimeKeys = array();
150 var $mRedirectCode = '';
152 var $mFeedLinksAppendQuery = null;
154 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
155 # @see ResourceLoaderModule::$origin
156 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
157 protected $mAllowedModules = array(
158 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
162 * @EasterEgg I just love the name for this self documenting variable.
165 var $mDoNothing = false;
168 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
171 * lazy initialised, use parserOptions()
174 protected $mParserOptions = null;
177 * Handles the atom / rss links.
178 * We probably only support atom in 2011.
179 * Looks like a private variable.
180 * @see $wgAdvertisedFeedTypes
182 var $mFeedLinks = array();
184 // Gwicke work on squid caching? Roughly from 2003.
185 var $mEnableClientCache = true;
188 * Flag if output should only contain the body of the article.
191 var $mArticleBodyOnly = false;
193 var $mNewSectionLink = false;
194 var $mHideNewSectionLink = false;
197 * Comes from the parser. This was probably made to load CSS/JS only
198 * if we had "<gallery>". Used directly in CategoryPage.php
199 * Looks like resource loader can replace this.
201 var $mNoGallery = false;
203 // should be private.
204 var $mPageTitleActionText = '';
205 var $mParseWarnings = array();
207 // Cache stuff. Looks like mEnableClientCache
208 var $mSquidMaxage = 0;
211 var $mPreventClickjacking = true;
213 /// should be private. To include the variable {{REVISIONID}}
214 var $mRevisionId = null;
215 private $mRevisionTimestamp = null;
217 var $mFileVersion = null;
220 * An array of stylesheet filenames (relative from skins path), with options
221 * for CSS media, IE conditions, and RTL/LTR direction.
222 * For internal use; add settings in the skin via $this->addStyle()
224 * Style again! This seems like a code duplication since we already have
225 * mStyles. This is what makes OpenSource amazing.
227 var $styles = array();
230 * Whether jQuery is already handled.
232 protected $mJQueryDone = false;
234 private $mIndexPolicy = 'index';
235 private $mFollowPolicy = 'follow';
236 private $mVaryHeader = array(
237 'Accept-Encoding' => array( 'list-contains=gzip' ),
241 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
246 private $mRedirectedFrom = null;
249 * Additional key => value data
251 private $mProperties = array();
254 * @var string|null: ResourceLoader target for load.php links. If null, will be omitted
256 private $mTarget = null;
259 * @var bool: Whether parser output should contain table of contents
261 private $mEnableTOC = true;
264 * @var bool: Whether parser output should contain section edit links
266 private $mEnableSectionEditLinks = true;
269 * Constructor for OutputPage. This should not be called directly.
270 * Instead a new RequestContext should be created and it will implicitly create
271 * a OutputPage tied to that context.
273 function __construct( IContextSource
$context = null ) {
274 if ( $context === null ) {
275 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
276 wfDeprecated( __METHOD__
, '1.18' );
278 $this->setContext( $context );
283 * Redirect to $url rather than displaying the normal page
285 * @param string $url URL
286 * @param string $responsecode HTTP status code
288 public function redirect( $url, $responsecode = '302' ) {
289 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
290 $this->mRedirect
= str_replace( "\n", '', $url );
291 $this->mRedirectCode
= $responsecode;
295 * Get the URL to redirect to, or an empty string if not redirect URL set
299 public function getRedirect() {
300 return $this->mRedirect
;
304 * Set the HTTP status code to send with the output.
306 * @param $statusCode Integer
308 public function setStatusCode( $statusCode ) {
309 $this->mStatusCode
= $statusCode;
313 * Add a new "<meta>" tag
314 * To add an http-equiv meta tag, precede the name with "http:"
316 * @param string $name tag name
317 * @param string $val tag value
319 function addMeta( $name, $val ) {
320 array_push( $this->mMetatags
, array( $name, $val ) );
324 * Add a new \<link\> tag to the page header.
326 * Note: use setCanonicalUrl() for rel=canonical.
328 * @param array $linkarr associative array of attributes.
330 function addLink( $linkarr ) {
331 array_push( $this->mLinktags
, $linkarr );
335 * Add a new \<link\> with "rel" attribute set to "meta"
337 * @param array $linkarr associative array mapping attribute names to their
338 * values, both keys and values will be escaped, and the
339 * "rel" attribute will be automatically added
341 function addMetadataLink( $linkarr ) {
342 $linkarr['rel'] = $this->getMetadataAttribute();
343 $this->addLink( $linkarr );
347 * Set the URL to be used for the <link rel=canonical>. This should be used
348 * in preference to addLink(), to avoid duplicate link tags.
350 function setCanonicalUrl( $url ) {
351 $this->mCanonicalUrl
= $url;
355 * Get the value of the "rel" attribute for metadata links
359 public function getMetadataAttribute() {
360 # note: buggy CC software only reads first "meta" link
361 static $haveMeta = false;
363 return 'alternate meta';
371 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
373 * @param string $script raw HTML
375 function addScript( $script ) {
376 $this->mScripts
.= $script . "\n";
380 * Register and add a stylesheet from an extension directory.
382 * @param string $url path to sheet. Provide either a full url (beginning
383 * with 'http', etc) or a relative path from the document root
384 * (beginning with '/'). Otherwise it behaves identically to
385 * addStyle() and draws from the /skins folder.
387 public function addExtensionStyle( $url ) {
388 array_push( $this->mExtStyles
, $url );
392 * Get all styles added by extensions
396 function getExtStyle() {
397 return $this->mExtStyles
;
401 * Add a JavaScript file out of skins/common, or a given relative path.
403 * @param string $file filename in skins/common or complete on-server path
405 * @param string $version style version of the file. Defaults to $wgStyleVersion
407 public function addScriptFile( $file, $version = null ) {
408 global $wgStylePath, $wgStyleVersion;
409 // See if $file parameter is an absolute URL or begins with a slash
410 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
413 $path = "{$wgStylePath}/common/{$file}";
415 if ( is_null( $version ) ) {
416 $version = $wgStyleVersion;
418 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
422 * Add a self-contained script tag with the given contents
424 * @param string $script JavaScript text, no "<script>" tags
426 public function addInlineScript( $script ) {
427 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
431 * Get all registered JS and CSS tags for the header.
435 function getScript() {
436 return $this->mScripts
. $this->getHeadItems();
440 * Filter an array of modules to remove insufficiently trustworthy members, and modules
441 * which are no longer registered (eg a page is cached before an extension is disabled)
442 * @param $modules Array
443 * @param string $position if not null, only return modules with this position
444 * @param $type string
447 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
) {
448 $resourceLoader = $this->getResourceLoader();
449 $filteredModules = array();
450 foreach ( $modules as $val ) {
451 $module = $resourceLoader->getModule( $val );
452 if ( $module instanceof ResourceLoaderModule
453 && $module->getOrigin() <= $this->getAllowedModules( $type )
454 && ( is_null( $position ) ||
$module->getPosition() == $position )
455 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) ) )
457 $filteredModules[] = $val;
460 return $filteredModules;
464 * Get the list of modules to include on this page
466 * @param bool $filter whether to filter out insufficiently trustworthy modules
467 * @param string $position if not null, only return modules with this position
468 * @param $param string
469 * @return Array of module names
471 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
472 $modules = array_values( array_unique( $this->$param ) );
474 ?
$this->filterModules( $modules, $position )
479 * Add one or more modules recognized by the resource loader. Modules added
480 * through this function will be loaded by the resource loader when the
483 * @param $modules Mixed: module name (string) or array of module names
485 public function addModules( $modules ) {
486 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
490 * Get the list of module JS to include on this page
495 * @return array of module names
497 public function getModuleScripts( $filter = false, $position = null ) {
498 return $this->getModules( $filter, $position, 'mModuleScripts' );
502 * Add only JS of one or more modules recognized by the resource loader. Module
503 * scripts added through this function will be loaded by the resource loader when
506 * @param $modules Mixed: module name (string) or array of module names
508 public function addModuleScripts( $modules ) {
509 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
513 * Get the list of module CSS to include on this page
518 * @return Array of module names
520 public function getModuleStyles( $filter = false, $position = null ) {
521 return $this->getModules( $filter, $position, 'mModuleStyles' );
525 * Add only CSS of one or more modules recognized by the resource loader.
527 * Module styles added through this function will be added using standard link CSS
528 * tags, rather than as a combined Javascript and CSS package. Thus, they will
529 * load when JavaScript is disabled (unless CSS also happens to be disabled).
531 * @param $modules Mixed: module name (string) or array of module names
533 public function addModuleStyles( $modules ) {
534 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
538 * Get the list of module messages to include on this page
543 * @return Array of module names
545 public function getModuleMessages( $filter = false, $position = null ) {
546 return $this->getModules( $filter, $position, 'mModuleMessages' );
550 * Add only messages of one or more modules recognized by the resource loader.
551 * Module messages added through this function will be loaded by the resource
552 * loader when the page loads.
554 * @param $modules Mixed: module name (string) or array of module names
556 public function addModuleMessages( $modules ) {
557 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
561 * @return null|string: ResourceLoader target
563 public function getTarget() {
564 return $this->mTarget
;
568 * Sets ResourceLoader target for load.php links. If null, will be omitted
570 * @param $target string|null
572 public function setTarget( $target ) {
573 $this->mTarget
= $target;
577 * Get an array of head items
581 function getHeadItemsArray() {
582 return $this->mHeadItems
;
586 * Get all header items in a string
590 function getHeadItems() {
592 foreach ( $this->mHeadItems
as $item ) {
599 * Add or replace an header item to the output
601 * @param string $name item name
602 * @param string $value raw HTML
604 public function addHeadItem( $name, $value ) {
605 $this->mHeadItems
[$name] = $value;
609 * Check if the header item $name is already set
611 * @param string $name item name
614 public function hasHeadItem( $name ) {
615 return isset( $this->mHeadItems
[$name] );
619 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
621 * @param string $tag value of "ETag" header
623 function setETag( $tag ) {
628 * Set whether the output should only contain the body of the article,
629 * without any skin, sidebar, etc.
630 * Used e.g. when calling with "action=render".
632 * @param $only Boolean: whether to output only the body of the article
634 public function setArticleBodyOnly( $only ) {
635 $this->mArticleBodyOnly
= $only;
639 * Return whether the output will contain only the body of the article
643 public function getArticleBodyOnly() {
644 return $this->mArticleBodyOnly
;
648 * Set an additional output property
651 * @param string $name
652 * @param mixed $value
654 public function setProperty( $name, $value ) {
655 $this->mProperties
[$name] = $value;
659 * Get an additional output property
663 * @return mixed: Property value or null if not found
665 public function getProperty( $name ) {
666 if ( isset( $this->mProperties
[$name] ) ) {
667 return $this->mProperties
[$name];
674 * checkLastModified tells the client to use the client-cached page if
675 * possible. If successful, the OutputPage is disabled so that
676 * any future call to OutputPage->output() have no effect.
678 * Side effect: sets mLastModified for Last-Modified header
680 * @param $timestamp string
682 * @return Boolean: true if cache-ok headers was sent.
684 public function checkLastModified( $timestamp ) {
685 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
687 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
688 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
691 if ( !$wgCachePages ) {
692 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
695 if ( $this->getUser()->getOption( 'nocache' ) ) {
696 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
700 $timestamp = wfTimestamp( TS_MW
, $timestamp );
701 $modifiedTimes = array(
702 'page' => $timestamp,
703 'user' => $this->getUser()->getTouched(),
704 'epoch' => $wgCacheEpoch
707 // bug 44570: the core page itself may not change, but resources might
708 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $wgSquidMaxage );
710 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
712 $maxModified = max( $modifiedTimes );
713 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
715 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
716 if ( $clientHeader === false ) {
717 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
721 # IE sends sizes after the date like this:
722 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
723 # this breaks strtotime().
724 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
726 wfSuppressWarnings(); // E_STRICT system time bitching
727 $clientHeaderTime = strtotime( $clientHeader );
729 if ( !$clientHeaderTime ) {
730 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
733 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
737 foreach ( $modifiedTimes as $name => $value ) {
738 if ( $info !== '' ) {
741 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
744 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
745 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
746 wfDebug( __METHOD__
. ": effective Last-Modified: " .
747 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
748 if ( $clientHeaderTime < $maxModified ) {
749 wfDebug( __METHOD__
. ": STALE, $info\n", false );
754 # Give a 304 response code and disable body output
755 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
756 ini_set( 'zlib.output_compression', 0 );
757 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
758 $this->sendCacheControl();
761 // Don't output a compressed blob when using ob_gzhandler;
762 // it's technically against HTTP spec and seems to confuse
763 // Firefox when the response gets split over two packets.
764 wfClearOutputBuffers();
770 * Override the last modified timestamp
772 * @param string $timestamp new timestamp, in a format readable by
775 public function setLastModified( $timestamp ) {
776 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
780 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
782 * @param string $policy the literal string to output as the contents of
783 * the meta tag. Will be parsed according to the spec and output in
787 public function setRobotPolicy( $policy ) {
788 $policy = Article
::formatRobotPolicy( $policy );
790 if ( isset( $policy['index'] ) ) {
791 $this->setIndexPolicy( $policy['index'] );
793 if ( isset( $policy['follow'] ) ) {
794 $this->setFollowPolicy( $policy['follow'] );
799 * Set the index policy for the page, but leave the follow policy un-
802 * @param string $policy Either 'index' or 'noindex'.
805 public function setIndexPolicy( $policy ) {
806 $policy = trim( $policy );
807 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
808 $this->mIndexPolicy
= $policy;
813 * Set the follow policy for the page, but leave the index policy un-
816 * @param string $policy either 'follow' or 'nofollow'.
819 public function setFollowPolicy( $policy ) {
820 $policy = trim( $policy );
821 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
822 $this->mFollowPolicy
= $policy;
827 * Set the new value of the "action text", this will be added to the
828 * "HTML title", separated from it with " - ".
830 * @param string $text new value of the "action text"
832 public function setPageTitleActionText( $text ) {
833 $this->mPageTitleActionText
= $text;
837 * Get the value of the "action text"
841 public function getPageTitleActionText() {
842 if ( isset( $this->mPageTitleActionText
) ) {
843 return $this->mPageTitleActionText
;
849 * "HTML title" means the contents of "<title>".
850 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
852 * @param $name string
854 public function setHTMLTitle( $name ) {
855 if ( $name instanceof Message
) {
856 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
858 $this->mHTMLtitle
= $name;
863 * Return the "HTML title", i.e. the content of the "<title>" tag.
867 public function getHTMLTitle() {
868 return $this->mHTMLtitle
;
872 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
876 public function setRedirectedFrom( $t ) {
877 $this->mRedirectedFrom
= $t;
881 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
882 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
883 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
884 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
886 * @param $name string|Message
888 public function setPageTitle( $name ) {
889 if ( $name instanceof Message
) {
890 $name = $name->setContext( $this->getContext() )->text();
893 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
894 # but leave "<i>foobar</i>" alone
895 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
896 $this->mPagetitle
= $nameWithTags;
898 # change "<i>foo&bar</i>" to "foo&bar"
899 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
903 * Return the "page title", i.e. the content of the \<h1\> tag.
907 public function getPageTitle() {
908 return $this->mPagetitle
;
912 * Set the Title object to use
914 * @param $t Title object
916 public function setTitle( Title
$t ) {
917 $this->getContext()->setTitle( $t );
921 * Replace the subtitle with $str
923 * @param string|Message $str new value of the subtitle. String should be safe HTML.
925 public function setSubtitle( $str ) {
926 $this->clearSubtitle();
927 $this->addSubtitle( $str );
931 * Add $str to the subtitle
933 * @deprecated in 1.19; use addSubtitle() instead
934 * @param string|Message $str to add to the subtitle
936 public function appendSubtitle( $str ) {
937 $this->addSubtitle( $str );
941 * Add $str to the subtitle
943 * @param string|Message $str to add to the subtitle. String should be safe HTML.
945 public function addSubtitle( $str ) {
946 if ( $str instanceof Message
) {
947 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
949 $this->mSubtitle
[] = $str;
954 * Add a subtitle containing a backlink to a page
956 * @param $title Title to link to
958 public function addBacklinkSubtitle( Title
$title ) {
960 if ( $title->isRedirect() ) {
961 $query['redirect'] = 'no';
963 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
967 * Clear the subtitles
969 public function clearSubtitle() {
970 $this->mSubtitle
= array();
978 public function getSubtitle() {
979 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
983 * Set the page as printable, i.e. it'll be displayed with with all
984 * print styles included
986 public function setPrintable() {
987 $this->mPrintable
= true;
991 * Return whether the page is "printable"
995 public function isPrintable() {
996 return $this->mPrintable
;
1000 * Disable output completely, i.e. calling output() will have no effect
1002 public function disable() {
1003 $this->mDoNothing
= true;
1007 * Return whether the output will be completely disabled
1011 public function isDisabled() {
1012 return $this->mDoNothing
;
1016 * Show an "add new section" link?
1020 public function showNewSectionLink() {
1021 return $this->mNewSectionLink
;
1025 * Forcibly hide the new section link?
1029 public function forceHideNewSectionLink() {
1030 return $this->mHideNewSectionLink
;
1034 * Add or remove feed links in the page header
1035 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1036 * for the new version
1037 * @see addFeedLink()
1039 * @param $show Boolean: true: add default feeds, false: remove all feeds
1041 public function setSyndicated( $show = true ) {
1043 $this->setFeedAppendQuery( false );
1045 $this->mFeedLinks
= array();
1050 * Add default feeds to the page header
1051 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1052 * for the new version
1053 * @see addFeedLink()
1055 * @param string $val query to append to feed links or false to output
1058 public function setFeedAppendQuery( $val ) {
1059 global $wgAdvertisedFeedTypes;
1061 $this->mFeedLinks
= array();
1063 foreach ( $wgAdvertisedFeedTypes as $type ) {
1064 $query = "feed=$type";
1065 if ( is_string( $val ) ) {
1066 $query .= '&' . $val;
1068 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1073 * Add a feed link to the page header
1075 * @param string $format feed type, should be a key of $wgFeedClasses
1076 * @param string $href URL
1078 public function addFeedLink( $format, $href ) {
1079 global $wgAdvertisedFeedTypes;
1081 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1082 $this->mFeedLinks
[$format] = $href;
1087 * Should we output feed links for this page?
1090 public function isSyndicated() {
1091 return count( $this->mFeedLinks
) > 0;
1095 * Return URLs for each supported syndication format for this page.
1096 * @return array associating format keys with URLs
1098 public function getSyndicationLinks() {
1099 return $this->mFeedLinks
;
1103 * Will currently always return null
1107 public function getFeedAppendQuery() {
1108 return $this->mFeedLinksAppendQuery
;
1112 * Set whether the displayed content is related to the source of the
1113 * corresponding article on the wiki
1114 * Setting true will cause the change "article related" toggle to true
1118 public function setArticleFlag( $v ) {
1119 $this->mIsarticle
= $v;
1121 $this->mIsArticleRelated
= $v;
1126 * Return whether the content displayed page is related to the source of
1127 * the corresponding article on the wiki
1131 public function isArticle() {
1132 return $this->mIsarticle
;
1136 * Set whether this page is related an article on the wiki
1137 * Setting false will cause the change of "article flag" toggle to false
1141 public function setArticleRelated( $v ) {
1142 $this->mIsArticleRelated
= $v;
1144 $this->mIsarticle
= false;
1149 * Return whether this page is related an article on the wiki
1153 public function isArticleRelated() {
1154 return $this->mIsArticleRelated
;
1158 * Add new language links
1160 * @param array $newLinkArray Associative array mapping language code to the page
1163 public function addLanguageLinks( $newLinkArray ) {
1164 $this->mLanguageLinks +
= $newLinkArray;
1168 * Reset the language links and add new language links
1170 * @param array $newLinkArray Associative array mapping language code to the page
1173 public function setLanguageLinks( $newLinkArray ) {
1174 $this->mLanguageLinks
= $newLinkArray;
1178 * Get the list of language links
1180 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1182 public function getLanguageLinks() {
1183 return $this->mLanguageLinks
;
1187 * Add an array of categories, with names in the keys
1189 * @param array $categories mapping category name => sort key
1191 public function addCategoryLinks( $categories ) {
1194 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1198 # Add the links to a LinkBatch
1199 $arr = array( NS_CATEGORY
=> $categories );
1200 $lb = new LinkBatch
;
1201 $lb->setArray( $arr );
1203 # Fetch existence plus the hiddencat property
1204 $dbr = wfGetDB( DB_SLAVE
);
1205 $res = $dbr->select( array( 'page', 'page_props' ),
1206 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1207 $lb->constructSet( 'page', $dbr ),
1210 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1213 # Add the results to the link cache
1214 $lb->addResultToCache( LinkCache
::singleton(), $res );
1216 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1217 $categories = array_combine(
1218 array_keys( $categories ),
1219 array_fill( 0, count( $categories ), 'normal' )
1222 # Mark hidden categories
1223 foreach ( $res as $row ) {
1224 if ( isset( $row->pp_value
) ) {
1225 $categories[$row->page_title
] = 'hidden';
1229 # Add the remaining categories to the skin
1230 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1231 foreach ( $categories as $category => $type ) {
1232 $origcategory = $category;
1233 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1234 $wgContLang->findVariantLink( $category, $title, true );
1235 if ( $category != $origcategory ) {
1236 if ( array_key_exists( $category, $categories ) ) {
1240 $text = $wgContLang->convertHtml( $title->getText() );
1241 $this->mCategories
[] = $title->getText();
1242 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1248 * Reset the category links (but not the category list) and add $categories
1250 * @param array $categories mapping category name => sort key
1252 public function setCategoryLinks( $categories ) {
1253 $this->mCategoryLinks
= array();
1254 $this->addCategoryLinks( $categories );
1258 * Get the list of category links, in a 2-D array with the following format:
1259 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1260 * hidden categories) and $link a HTML fragment with a link to the category
1265 public function getCategoryLinks() {
1266 return $this->mCategoryLinks
;
1270 * Get the list of category names this page belongs to
1272 * @return Array of strings
1274 public function getCategories() {
1275 return $this->mCategories
;
1279 * Do not allow scripts which can be modified by wiki users to load on this page;
1280 * only allow scripts bundled with, or generated by, the software.
1282 public function disallowUserJs() {
1283 $this->reduceAllowedModules(
1284 ResourceLoaderModule
::TYPE_SCRIPTS
,
1285 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1290 * Return whether user JavaScript is allowed for this page
1291 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1292 * trustworthiness is identified and enforced automagically.
1295 public function isUserJsAllowed() {
1296 wfDeprecated( __METHOD__
, '1.18' );
1297 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1301 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1302 * @see ResourceLoaderModule::$origin
1303 * @param string $type ResourceLoaderModule TYPE_ constant
1304 * @return Int ResourceLoaderModule ORIGIN_ class constant
1306 public function getAllowedModules( $type ) {
1307 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1308 return min( array_values( $this->mAllowedModules
) );
1310 return isset( $this->mAllowedModules
[$type] )
1311 ?
$this->mAllowedModules
[$type]
1312 : ResourceLoaderModule
::ORIGIN_ALL
;
1317 * Set the highest level of CSS/JS untrustworthiness allowed
1318 * @param $type String ResourceLoaderModule TYPE_ constant
1319 * @param $level Int ResourceLoaderModule class constant
1321 public function setAllowedModules( $type, $level ) {
1322 $this->mAllowedModules
[$type] = $level;
1326 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1327 * @param $type String
1328 * @param $level Int ResourceLoaderModule class constant
1330 public function reduceAllowedModules( $type, $level ) {
1331 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1335 * Prepend $text to the body HTML
1337 * @param string $text HTML
1339 public function prependHTML( $text ) {
1340 $this->mBodytext
= $text . $this->mBodytext
;
1344 * Append $text to the body HTML
1346 * @param string $text HTML
1348 public function addHTML( $text ) {
1349 $this->mBodytext
.= $text;
1353 * Shortcut for adding an Html::element via addHTML.
1357 * @param $element string
1358 * @param $attribs array
1359 * @param $contents string
1361 public function addElement( $element, $attribs = array(), $contents = '' ) {
1362 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1366 * Clear the body HTML
1368 public function clearHTML() {
1369 $this->mBodytext
= '';
1375 * @return String: HTML
1377 public function getHTML() {
1378 return $this->mBodytext
;
1382 * Get/set the ParserOptions object to use for wikitext parsing
1384 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1385 * current ParserOption object
1386 * @return ParserOptions object
1388 public function parserOptions( $options = null ) {
1389 if ( !$this->mParserOptions
) {
1390 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1391 $this->mParserOptions
->setEditSection( false );
1393 return wfSetVar( $this->mParserOptions
, $options );
1397 * Set the revision ID which will be seen by the wiki text parser
1398 * for things such as embedded {{REVISIONID}} variable use.
1400 * @param $revid Mixed: an positive integer, or null
1401 * @return Mixed: previous value
1403 public function setRevisionId( $revid ) {
1404 $val = is_null( $revid ) ?
null : intval( $revid );
1405 return wfSetVar( $this->mRevisionId
, $val );
1409 * Get the displayed revision ID
1413 public function getRevisionId() {
1414 return $this->mRevisionId
;
1418 * Set the timestamp of the revision which will be displayed. This is used
1419 * to avoid a extra DB call in Skin::lastModified().
1421 * @param $timestamp Mixed: string, or null
1422 * @return Mixed: previous value
1424 public function setRevisionTimestamp( $timestamp ) {
1425 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1429 * Get the timestamp of displayed revision.
1430 * This will be null if not filled by setRevisionTimestamp().
1432 * @return String or null
1434 public function getRevisionTimestamp() {
1435 return $this->mRevisionTimestamp
;
1439 * Set the displayed file version
1441 * @param $file File|bool
1442 * @return Mixed: previous value
1444 public function setFileVersion( $file ) {
1446 if ( $file instanceof File
&& $file->exists() ) {
1447 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1449 return wfSetVar( $this->mFileVersion
, $val, true );
1453 * Get the displayed file version
1455 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1457 public function getFileVersion() {
1458 return $this->mFileVersion
;
1462 * Get the templates used on this page
1464 * @return Array (namespace => dbKey => revId)
1467 public function getTemplateIds() {
1468 return $this->mTemplateIds
;
1472 * Get the files used on this page
1474 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1477 public function getFileSearchOptions() {
1478 return $this->mImageTimeKeys
;
1482 * Convert wikitext to HTML and add it to the buffer
1483 * Default assumes that the current page title will be used.
1485 * @param $text String
1486 * @param $linestart Boolean: is this the start of a line?
1487 * @param $interface Boolean: is this text in the user interface language?
1489 public function addWikiText( $text, $linestart = true, $interface = true ) {
1490 $title = $this->getTitle(); // Work around E_STRICT
1492 throw new MWException( 'Title is null' );
1494 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1498 * Add wikitext with a custom Title object
1500 * @param string $text wikitext
1501 * @param $title Title object
1502 * @param $linestart Boolean: is this the start of a line?
1504 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1505 $this->addWikiTextTitle( $text, $title, $linestart );
1509 * Add wikitext with a custom Title object and tidy enabled.
1511 * @param string $text wikitext
1512 * @param $title Title object
1513 * @param $linestart Boolean: is this the start of a line?
1515 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1516 $this->addWikiTextTitle( $text, $title, $linestart, true );
1520 * Add wikitext with tidy enabled
1522 * @param string $text wikitext
1523 * @param $linestart Boolean: is this the start of a line?
1525 public function addWikiTextTidy( $text, $linestart = true ) {
1526 $title = $this->getTitle();
1527 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1531 * Add wikitext with a custom Title object
1533 * @param string $text wikitext
1534 * @param $title Title object
1535 * @param $linestart Boolean: is this the start of a line?
1536 * @param $tidy Boolean: whether to use tidy
1537 * @param $interface Boolean: whether it is an interface message
1538 * (for example disables conversion)
1540 public function addWikiTextTitle( $text, Title
$title, $linestart, $tidy = false, $interface = false ) {
1543 wfProfileIn( __METHOD__
);
1545 $popts = $this->parserOptions();
1546 $oldTidy = $popts->setTidy( $tidy );
1547 $popts->setInterfaceMessage( (bool)$interface );
1549 $parserOutput = $wgParser->parse(
1550 $text, $title, $popts,
1551 $linestart, true, $this->mRevisionId
1554 $popts->setTidy( $oldTidy );
1556 $this->addParserOutput( $parserOutput );
1558 wfProfileOut( __METHOD__
);
1562 * Add a ParserOutput object, but without Html
1564 * @param $parserOutput ParserOutput object
1566 public function addParserOutputNoText( &$parserOutput ) {
1567 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1568 $this->addCategoryLinks( $parserOutput->getCategories() );
1569 $this->mNewSectionLink
= $parserOutput->getNewSection();
1570 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1572 $this->mParseWarnings
= $parserOutput->getWarnings();
1573 if ( !$parserOutput->isCacheable() ) {
1574 $this->enableClientCache( false );
1576 $this->mNoGallery
= $parserOutput->getNoGallery();
1577 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1578 $this->addModules( $parserOutput->getModules() );
1579 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1580 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1581 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1583 // Template versioning...
1584 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1585 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1586 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1588 $this->mTemplateIds
[$ns] = $dbks;
1591 // File versioning...
1592 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1593 $this->mImageTimeKeys
[$dbk] = $data;
1596 // Hooks registered in the object
1597 global $wgParserOutputHooks;
1598 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1599 list( $hookName, $data ) = $hookInfo;
1600 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1601 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1605 // Link flags are ignored for now, but may in the future be
1606 // used to mark individual language links.
1607 $linkFlags = array();
1608 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1609 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1613 * Add a ParserOutput object
1615 * @param $parserOutput ParserOutput
1617 function addParserOutput( &$parserOutput ) {
1618 $this->addParserOutputNoText( $parserOutput );
1619 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1620 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1621 $text = $parserOutput->getText();
1622 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1623 $this->addHTML( $text );
1627 * Add the output of a QuickTemplate to the output buffer
1629 * @param $template QuickTemplate
1631 public function addTemplate( &$template ) {
1632 $this->addHTML( $template->getHTML() );
1636 * Parse wikitext and return the HTML.
1638 * @param $text String
1639 * @param $linestart Boolean: is this the start of a line?
1640 * @param $interface Boolean: use interface language ($wgLang instead of
1641 * $wgContLang) while parsing language sensitive magic
1642 * words like GRAMMAR and PLURAL. This also disables
1643 * LanguageConverter.
1644 * @param $language Language object: target language object, will override
1646 * @throws MWException
1647 * @return String: HTML
1649 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1652 if ( is_null( $this->getTitle() ) ) {
1653 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1656 $popts = $this->parserOptions();
1658 $popts->setInterfaceMessage( true );
1660 if ( $language !== null ) {
1661 $oldLang = $popts->setTargetLanguage( $language );
1664 $parserOutput = $wgParser->parse(
1665 $text, $this->getTitle(), $popts,
1666 $linestart, true, $this->mRevisionId
1670 $popts->setInterfaceMessage( false );
1672 if ( $language !== null ) {
1673 $popts->setTargetLanguage( $oldLang );
1676 return $parserOutput->getText();
1680 * Parse wikitext, strip paragraphs, and return the HTML.
1682 * @param $text String
1683 * @param $linestart Boolean: is this the start of a line?
1684 * @param $interface Boolean: use interface language ($wgLang instead of
1685 * $wgContLang) while parsing language sensitive magic
1686 * words like GRAMMAR and PLURAL
1687 * @return String: HTML
1689 public function parseInline( $text, $linestart = true, $interface = false ) {
1690 $parsed = $this->parse( $text, $linestart, $interface );
1693 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1701 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1703 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1705 public function setSquidMaxage( $maxage ) {
1706 $this->mSquidMaxage
= $maxage;
1710 * Use enableClientCache(false) to force it to send nocache headers
1712 * @param $state bool
1716 public function enableClientCache( $state ) {
1717 return wfSetVar( $this->mEnableClientCache
, $state );
1721 * Get the list of cookies that will influence on the cache
1725 function getCacheVaryCookies() {
1726 global $wgCookiePrefix, $wgCacheVaryCookies;
1728 if ( $cookies === null ) {
1729 $cookies = array_merge(
1731 "{$wgCookiePrefix}Token",
1732 "{$wgCookiePrefix}LoggedOut",
1738 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1744 * Check if the request has a cache-varying cookie header
1745 * If it does, it's very important that we don't allow public caching
1749 function haveCacheVaryCookies() {
1750 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1751 if ( $cookieHeader === false ) {
1754 $cvCookies = $this->getCacheVaryCookies();
1755 foreach ( $cvCookies as $cookieName ) {
1756 # Check for a simple string match, like the way squid does it
1757 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1758 wfDebug( __METHOD__
. ": found $cookieName\n" );
1762 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1767 * Add an HTTP header that will influence on the cache
1769 * @param string $header header name
1770 * @param $option Array|null
1771 * @todo FIXME: Document the $option parameter; it appears to be for
1772 * X-Vary-Options but what format is acceptable?
1774 public function addVaryHeader( $header, $option = null ) {
1775 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1776 $this->mVaryHeader
[$header] = (array)$option;
1777 } elseif ( is_array( $option ) ) {
1778 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1779 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1781 $this->mVaryHeader
[$header] = $option;
1784 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1788 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1789 * such as Accept-Encoding or Cookie
1793 public function getVaryHeader() {
1794 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1798 * Get a complete X-Vary-Options header
1802 public function getXVO() {
1803 $cvCookies = $this->getCacheVaryCookies();
1805 $cookiesOption = array();
1806 foreach ( $cvCookies as $cookieName ) {
1807 $cookiesOption[] = 'string-contains=' . $cookieName;
1809 $this->addVaryHeader( 'Cookie', $cookiesOption );
1812 foreach ( $this->mVaryHeader
as $header => $option ) {
1813 $newheader = $header;
1814 if ( is_array( $option ) && count( $option ) > 0 ) {
1815 $newheader .= ';' . implode( ';', $option );
1817 $headers[] = $newheader;
1819 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1825 * bug 21672: Add Accept-Language to Vary and XVO headers
1826 * if there's no 'variant' parameter existed in GET.
1829 * /w/index.php?title=Main_page should always be served; but
1830 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1832 function addAcceptLanguage() {
1833 $lang = $this->getTitle()->getPageLanguage();
1834 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1835 $variants = $lang->getVariants();
1836 $aloption = array();
1837 foreach ( $variants as $variant ) {
1838 if ( $variant === $lang->getCode() ) {
1841 $aloption[] = 'string-contains=' . $variant;
1843 // IE and some other browsers use BCP 47 standards in
1844 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1845 // We should handle these too.
1846 $variantBCP47 = wfBCP47( $variant );
1847 if ( $variantBCP47 !== $variant ) {
1848 $aloption[] = 'string-contains=' . $variantBCP47;
1852 $this->addVaryHeader( 'Accept-Language', $aloption );
1857 * Set a flag which will cause an X-Frame-Options header appropriate for
1858 * edit pages to be sent. The header value is controlled by
1859 * $wgEditPageFrameOptions.
1861 * This is the default for special pages. If you display a CSRF-protected
1862 * form on an ordinary view page, then you need to call this function.
1864 * @param $enable bool
1866 public function preventClickjacking( $enable = true ) {
1867 $this->mPreventClickjacking
= $enable;
1871 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1872 * This can be called from pages which do not contain any CSRF-protected
1875 public function allowClickjacking() {
1876 $this->mPreventClickjacking
= false;
1880 * Get the X-Frame-Options header value (without the name part), or false
1881 * if there isn't one. This is used by Skin to determine whether to enable
1882 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1886 public function getFrameOptions() {
1887 global $wgBreakFrames, $wgEditPageFrameOptions;
1888 if ( $wgBreakFrames ) {
1890 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1891 return $wgEditPageFrameOptions;
1897 * Send cache control HTTP headers
1899 public function sendCacheControl() {
1900 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1902 $response = $this->getRequest()->response();
1903 if ( $wgUseETag && $this->mETag
) {
1904 $response->header( "ETag: $this->mETag" );
1907 $this->addVaryHeader( 'Cookie' );
1908 $this->addAcceptLanguage();
1910 # don't serve compressed data to clients who can't handle it
1911 # maintain different caches for logged-in users and non-logged in ones
1912 $response->header( $this->getVaryHeader() );
1915 # Add an X-Vary-Options header for Squid with Wikimedia patches
1916 $response->header( $this->getXVO() );
1919 if ( $this->mEnableClientCache
) {
1921 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1922 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1925 # We'll purge the proxy cache explicitly, but require end user agents
1926 # to revalidate against the proxy on each visit.
1927 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1928 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1929 # start with a shorter timeout for initial testing
1930 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1931 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
1932 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1934 # We'll purge the proxy cache for anons explicitly, but require end user agents
1935 # to revalidate against the proxy on each visit.
1936 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1937 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1938 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1939 # start with a shorter timeout for initial testing
1940 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1941 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0' );
1944 # We do want clients to cache if they can, but they *must* check for updates
1945 # on revisiting the page.
1946 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1947 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1948 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1950 if ( $this->mLastModified
) {
1951 $response->header( "Last-Modified: {$this->mLastModified}" );
1954 wfDebug( __METHOD__
. ": no caching **\n", false );
1956 # In general, the absence of a last modified header should be enough to prevent
1957 # the client from using its cache. We send a few other things just to make sure.
1958 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1959 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1960 $response->header( 'Pragma: no-cache' );
1965 * Get the message associated with the HTTP response code $code
1967 * @param $code Integer: status code
1968 * @return String or null: message or null if $code is not in the list of
1971 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1973 public static function getStatusMessage( $code ) {
1974 wfDeprecated( __METHOD__
, '1.18' );
1975 return HttpStatus
::getMessage( $code );
1979 * Finally, all the text has been munged and accumulated into
1980 * the object, let's actually output it:
1982 public function output() {
1983 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
1984 $wgUseAjax, $wgResponsiveImages;
1986 if ( $this->mDoNothing
) {
1990 wfProfileIn( __METHOD__
);
1992 $response = $this->getRequest()->response();
1994 if ( $this->mRedirect
!= '' ) {
1995 # Standards require redirect URLs to be absolute
1996 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1998 $redirect = $this->mRedirect
;
1999 $code = $this->mRedirectCode
;
2001 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2002 if ( $code == '301' ||
$code == '303' ) {
2003 if ( !$wgDebugRedirects ) {
2004 $message = HttpStatus
::getMessage( $code );
2005 $response->header( "HTTP/1.1 $code $message" );
2007 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2009 if ( $wgVaryOnXFP ) {
2010 $this->addVaryHeader( 'X-Forwarded-Proto' );
2012 $this->sendCacheControl();
2014 $response->header( "Content-Type: text/html; charset=utf-8" );
2015 if ( $wgDebugRedirects ) {
2016 $url = htmlspecialchars( $redirect );
2017 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2018 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2019 print "</body>\n</html>\n";
2021 $response->header( 'Location: ' . $redirect );
2025 wfProfileOut( __METHOD__
);
2027 } elseif ( $this->mStatusCode
) {
2028 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2030 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2034 # Buffer output; final headers may depend on later processing
2037 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2038 $response->header( 'Content-language: ' . $wgLanguageCode );
2040 // Prevent framing, if requested
2041 $frameOptions = $this->getFrameOptions();
2042 if ( $frameOptions ) {
2043 $response->header( "X-Frame-Options: $frameOptions" );
2046 if ( $this->mArticleBodyOnly
) {
2047 echo $this->mBodytext
;
2050 $sk = $this->getSkin();
2051 // add skin specific modules
2052 $modules = $sk->getDefaultModules();
2054 // enforce various default modules for all skins
2055 $coreModules = array(
2056 // keep this list as small as possible
2057 'mediawiki.page.startup',
2061 // Support for high-density display images if enabled
2062 if ( $wgResponsiveImages ) {
2063 $coreModules[] = 'mediawiki.hidpi';
2066 $this->addModules( $coreModules );
2067 foreach ( $modules as $group ) {
2068 $this->addModules( $group );
2070 MWDebug
::addModules( $this );
2072 // FIXME: deprecate? - not clear why this is useful
2073 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2076 // Hook that allows last minute changes to the output page, e.g.
2077 // adding of CSS or Javascript by extensions.
2078 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2080 wfProfileIn( 'Output-skin' );
2082 wfProfileOut( 'Output-skin' );
2085 // This hook allows last minute changes to final overall output by modifying output buffer
2086 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2088 $this->sendCacheControl();
2092 wfProfileOut( __METHOD__
);
2096 * Actually output something with print.
2098 * @param string $ins the string to output
2099 * @deprecated since 1.22 Use echo yourself.
2101 public function out( $ins ) {
2102 wfDeprecated( __METHOD__
, '1.22' );
2107 * Produce a "user is blocked" page.
2108 * @deprecated since 1.18
2110 function blockedPage() {
2111 throw new UserBlockedError( $this->getUser()->mBlock
);
2115 * Prepare this object to display an error page; disable caching and
2116 * indexing, clear the current text and redirect, set the page's title
2117 * and optionally an custom HTML title (content of the "<title>" tag).
2119 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2120 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2121 * optional, if not passed the "<title>" attribute will be
2122 * based on $pageTitle
2124 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2125 $this->setPageTitle( $pageTitle );
2126 if ( $htmlTitle !== false ) {
2127 $this->setHTMLTitle( $htmlTitle );
2129 $this->setRobotPolicy( 'noindex,nofollow' );
2130 $this->setArticleRelated( false );
2131 $this->enableClientCache( false );
2132 $this->mRedirect
= '';
2133 $this->clearSubtitle();
2138 * Output a standard error page
2140 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2141 * showErrorPage( 'titlemsg', $messageObject );
2142 * showErrorPage( $titleMessageObj, $messageObject );
2144 * @param $title Mixed: message key (string) for page title, or a Message object
2145 * @param $msg Mixed: message key (string) for page text, or a Message object
2146 * @param array $params message parameters; ignored if $msg is a Message object
2148 public function showErrorPage( $title, $msg, $params = array() ) {
2149 if ( !$title instanceof Message
) {
2150 $title = $this->msg( $title );
2153 $this->prepareErrorPage( $title );
2155 if ( $msg instanceof Message
) {
2156 $this->addHTML( $msg->parseAsBlock() );
2158 $this->addWikiMsgArray( $msg, $params );
2161 $this->returnToMain();
2165 * Output a standard permission error page
2167 * @param array $errors error message keys
2168 * @param string $action action that was denied or null if unknown
2170 public function showPermissionsErrorPage( $errors, $action = null ) {
2171 // For some action (read, edit, create and upload), display a "login to do this action"
2172 // error if all of the following conditions are met:
2173 // 1. the user is not logged in
2174 // 2. the only error is insufficient permissions (i.e. no block or something else)
2175 // 3. the error can be avoided simply by logging in
2176 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2177 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2178 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2179 && ( User
::groupHasPermission( 'user', $action )
2180 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2182 $displayReturnto = null;
2184 # Due to bug 32276, if a user does not have read permissions,
2185 # $this->getTitle() will just give Special:Badtitle, which is
2186 # not especially useful as a returnto parameter. Use the title
2187 # from the request instead, if there was one.
2188 $request = $this->getRequest();
2189 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2190 if ( $action == 'edit' ) {
2191 $msg = 'whitelistedittext';
2192 $displayReturnto = $returnto;
2193 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2194 $msg = 'nocreatetext';
2195 } elseif ( $action == 'upload' ) {
2196 $msg = 'uploadnologintext';
2198 $msg = 'loginreqpagetext';
2199 $displayReturnto = Title
::newMainPage();
2205 $query['returnto'] = $returnto->getPrefixedText();
2207 if ( !$request->wasPosted() ) {
2208 $returntoquery = $request->getValues();
2209 unset( $returntoquery['title'] );
2210 unset( $returntoquery['returnto'] );
2211 unset( $returntoquery['returntoquery'] );
2212 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2215 $loginLink = Linker
::linkKnown(
2216 SpecialPage
::getTitleFor( 'Userlogin' ),
2217 $this->msg( 'loginreqlink' )->escaped(),
2222 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2223 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2225 # Don't return to a page the user can't read otherwise
2226 # we'll end up in a pointless loop
2227 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2228 $this->returnToMain( null, $displayReturnto );
2231 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2232 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2237 * Display an error page indicating that a given version of MediaWiki is
2238 * required to use it
2240 * @param $version Mixed: the version of MediaWiki needed to use the page
2242 public function versionRequired( $version ) {
2243 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2245 $this->addWikiMsg( 'versionrequiredtext', $version );
2246 $this->returnToMain();
2250 * Display an error page noting that a given permission bit is required.
2251 * @deprecated since 1.18, just throw the exception directly
2252 * @param string $permission key required
2253 * @throws PermissionsError
2255 public function permissionRequired( $permission ) {
2256 throw new PermissionsError( $permission );
2260 * Produce the stock "please login to use the wiki" page
2262 * @deprecated in 1.19; throw the exception directly
2264 public function loginToUse() {
2265 throw new PermissionsError( 'read' );
2269 * Format a list of error messages
2271 * @param array $errors of arrays returned by Title::getUserPermissionsErrors
2272 * @param string $action action that was denied or null if unknown
2273 * @return String: the wikitext error-messages, formatted into a list.
2275 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2276 if ( $action == null ) {
2277 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2279 $action_desc = $this->msg( "action-$action" )->plain();
2281 'permissionserrorstext-withaction',
2284 )->plain() . "\n\n";
2287 if ( count( $errors ) > 1 ) {
2288 $text .= '<ul class="permissions-errors">' . "\n";
2290 foreach ( $errors as $error ) {
2292 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2297 $text .= "<div class=\"permissions-errors\">\n" .
2298 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2306 * Display a page stating that the Wiki is in read-only mode,
2307 * and optionally show the source of the page that the user
2308 * was trying to edit. Should only be called (for this
2309 * purpose) after wfReadOnly() has returned true.
2311 * For historical reasons, this function is _also_ used to
2312 * show the error message when a user tries to edit a page
2313 * they are not allowed to edit. (Unless it's because they're
2314 * blocked, then we show blockedPage() instead.) In this
2315 * case, the second parameter should be set to true and a list
2316 * of reasons supplied as the third parameter.
2318 * @todo Needs to be split into multiple functions.
2320 * @param $source String: source code to show (or null).
2321 * @param $protected Boolean: is this a permissions error?
2322 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2323 * @param $action String: action that was denied or null if unknown
2324 * @throws ReadOnlyError
2326 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2327 $this->setRobotPolicy( 'noindex,nofollow' );
2328 $this->setArticleRelated( false );
2330 // If no reason is given, just supply a default "I can't let you do
2331 // that, Dave" message. Should only occur if called by legacy code.
2332 if ( $protected && empty( $reasons ) ) {
2333 $reasons[] = array( 'badaccess-group0' );
2336 if ( !empty( $reasons ) ) {
2337 // Permissions error
2339 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2340 $this->addBacklinkSubtitle( $this->getTitle() );
2342 $this->setPageTitle( $this->msg( 'badaccess' ) );
2344 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2346 // Wiki is read only
2347 throw new ReadOnlyError
;
2350 // Show source, if supplied
2351 if ( is_string( $source ) ) {
2352 $this->addWikiMsg( 'viewsourcetext' );
2354 $pageLang = $this->getTitle()->getPageLanguage();
2356 'id' => 'wpTextbox1',
2357 'name' => 'wpTextbox1',
2358 'cols' => $this->getUser()->getOption( 'cols' ),
2359 'rows' => $this->getUser()->getOption( 'rows' ),
2360 'readonly' => 'readonly',
2361 'lang' => $pageLang->getHtmlCode(),
2362 'dir' => $pageLang->getDir(),
2364 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2366 // Show templates used by this article
2367 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2368 $this->addHTML( "<div class='templatesUsed'>
2374 # If the title doesn't exist, it's fairly pointless to print a return
2375 # link to it. After all, you just tried editing it and couldn't, so
2376 # what's there to do there?
2377 if ( $this->getTitle()->exists() ) {
2378 $this->returnToMain( null, $this->getTitle() );
2383 * Turn off regular page output and return an error response
2384 * for when rate limiting has triggered.
2386 public function rateLimited() {
2387 throw new ThrottledError
;
2391 * Show a warning about slave lag
2393 * If the lag is higher than $wgSlaveLagCritical seconds,
2394 * then the warning is a bit more obvious. If the lag is
2395 * lower than $wgSlaveLagWarning, then no warning is shown.
2397 * @param $lag Integer: slave lag
2399 public function showLagWarning( $lag ) {
2400 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2401 if ( $lag >= $wgSlaveLagWarning ) {
2402 $message = $lag < $wgSlaveLagCritical
2405 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2406 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2410 public function showFatalError( $message ) {
2411 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2413 $this->addHTML( $message );
2416 public function showUnexpectedValueError( $name, $val ) {
2417 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2420 public function showFileCopyError( $old, $new ) {
2421 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2424 public function showFileRenameError( $old, $new ) {
2425 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2428 public function showFileDeleteError( $name ) {
2429 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2432 public function showFileNotFoundError( $name ) {
2433 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2437 * Add a "return to" link pointing to a specified title
2439 * @param $title Title to link
2440 * @param array $query query string parameters
2441 * @param string $text text of the link (input is not escaped)
2442 * @param $options Options array to pass to Linker
2444 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2445 $link = $this->msg( 'returnto' )->rawParams(
2446 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2447 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2451 * Add a "return to" link pointing to a specified title,
2452 * or the title indicated in the request, or else the main page
2455 * @param $returnto Title or String to return to
2456 * @param string $returntoquery query string for the return to link
2458 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2459 if ( $returnto == null ) {
2460 $returnto = $this->getRequest()->getText( 'returnto' );
2463 if ( $returntoquery == null ) {
2464 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2467 if ( $returnto === '' ) {
2468 $returnto = Title
::newMainPage();
2471 if ( is_object( $returnto ) ) {
2472 $titleObj = $returnto;
2474 $titleObj = Title
::newFromText( $returnto );
2476 if ( !is_object( $titleObj ) ) {
2477 $titleObj = Title
::newMainPage();
2480 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2484 * @param $sk Skin The given Skin
2485 * @param $includeStyle Boolean: unused
2486 * @return String: The doctype, opening "<html>", and head element.
2488 public function headElement( Skin
$sk, $includeStyle = true ) {
2489 global $wgContLang, $wgMimeType;
2491 $userdir = $this->getLanguage()->getDir();
2492 $sitedir = $wgContLang->getDir();
2494 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2496 if ( $this->getHTMLTitle() == '' ) {
2497 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2500 $openHead = Html
::openElement( 'head' );
2502 # Don't bother with the newline if $head == ''
2503 $ret .= "$openHead\n";
2506 if ( !Html
::isXmlMimeType( $wgMimeType ) ) {
2507 // Add <meta charset="UTF-8">
2508 // This should be before <title> since it defines the charset used by
2509 // text including the text inside <title>.
2510 // The spec recommends defining XHTML5's charset using the XML declaration
2512 // Our XML declaration is output by Html::htmlHeader.
2513 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2514 // http://www.whatwg.org/html/semantics.html#charset
2515 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2518 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2520 $ret .= implode( "\n", array(
2521 $this->getHeadLinks(),
2522 $this->buildCssLinks(),
2523 $this->getHeadScripts(),
2524 $this->getHeadItems()
2527 $closeHead = Html
::closeElement( 'head' );
2529 $ret .= "$closeHead\n";
2532 $bodyClasses = array();
2533 $bodyClasses[] = 'mediawiki';
2535 # Classes for LTR/RTL directionality support
2536 $bodyClasses[] = $userdir;
2537 $bodyClasses[] = "sitedir-$sitedir";
2539 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2540 # A <body> class is probably not the best way to do this . . .
2541 $bodyClasses[] = 'capitalize-all-nouns';
2544 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2545 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2546 $bodyClasses[] = 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2548 $bodyAttrs = array();
2549 // While the implode() is not strictly needed, it's used for backwards compatibility
2550 // (this used to be built as a string and hooks likely still expect that).
2551 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2553 // Allow skins and extensions to add body attributes they need
2554 $sk->addToBodyAttributes( $this, $bodyAttrs );
2555 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2557 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2563 * Get a ResourceLoader object associated with this OutputPage
2565 * @return ResourceLoader
2567 public function getResourceLoader() {
2568 if ( is_null( $this->mResourceLoader
) ) {
2569 $this->mResourceLoader
= new ResourceLoader();
2571 return $this->mResourceLoader
;
2576 * @param $modules Array/string with the module name(s)
2577 * @param string $only ResourceLoaderModule TYPE_ class constant
2578 * @param $useESI boolean
2579 * @param array $extraQuery with extra query parameters to add to each request. array( param => value )
2580 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2581 * @return string html "<script>" and "<style>" tags
2583 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2584 global $wgResourceLoaderUseESI;
2586 $modules = (array)$modules;
2588 if ( !count( $modules ) ) {
2592 if ( count( $modules ) > 1 ) {
2593 // Remove duplicate module requests
2594 $modules = array_unique( $modules );
2595 // Sort module names so requests are more uniform
2598 if ( ResourceLoader
::inDebugMode() ) {
2599 // Recursively call us for every item
2601 foreach ( $modules as $name ) {
2602 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2607 if ( !is_null( $this->mTarget
) ) {
2608 $extraQuery['target'] = $this->mTarget
;
2611 // Create keyed-by-group list of module objects from modules list
2613 $resourceLoader = $this->getResourceLoader();
2614 foreach ( $modules as $name ) {
2615 $module = $resourceLoader->getModule( $name );
2616 # Check that we're allowed to include this module on this page
2618 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2619 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2620 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2621 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2622 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2627 $group = $module->getGroup();
2628 if ( !isset( $groups[$group] ) ) {
2629 $groups[$group] = array();
2631 $groups[$group][$name] = $module;
2635 foreach ( $groups as $group => $grpModules ) {
2636 // Special handling for user-specific groups
2638 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2639 $user = $this->getUser()->getName();
2642 // Create a fake request based on the one we are about to make so modules return
2643 // correct timestamp and emptiness data
2644 $query = ResourceLoader
::makeLoaderQuery(
2645 array(), // modules; not determined yet
2646 $this->getLanguage()->getCode(),
2647 $this->getSkin()->getSkinName(),
2649 null, // version; not determined yet
2650 ResourceLoader
::inDebugMode(),
2651 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2652 $this->isPrintable(),
2653 $this->getRequest()->getBool( 'handheld' ),
2656 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2657 // Extract modules that know they're empty
2658 $emptyModules = array();
2659 foreach ( $grpModules as $key => $module ) {
2660 if ( $module->isKnownEmpty( $context ) ) {
2661 $emptyModules[$key] = 'ready';
2662 unset( $grpModules[$key] );
2665 // Inline empty modules: since they're empty, just mark them as 'ready'
2666 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2667 // If we're only getting the styles, we don't need to do anything for empty modules.
2668 $links .= Html
::inlineScript(
2669 ResourceLoader
::makeLoaderConditionalScript(
2670 ResourceLoader
::makeLoaderStateScript( $emptyModules )
2675 // If there are no modules left, skip this group
2676 if ( count( $grpModules ) === 0 ) {
2680 // Inline private modules. These can't be loaded through load.php for security
2681 // reasons, see bug 34907. Note that these modules should be loaded from
2682 // getHeadScripts() before the first loader call. Otherwise other modules can't
2683 // properly use them as dependencies (bug 30914)
2684 if ( $group === 'private' ) {
2685 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2686 $links .= Html
::inlineStyle(
2687 $resourceLoader->makeModuleResponse( $context, $grpModules )
2690 $links .= Html
::inlineScript(
2691 ResourceLoader
::makeLoaderConditionalScript(
2692 $resourceLoader->makeModuleResponse( $context, $grpModules )
2699 // Special handling for the user group; because users might change their stuff
2700 // on-wiki like user pages, or user preferences; we need to find the highest
2701 // timestamp of these user-changeable modules so we can ensure cache misses on change
2702 // This should NOT be done for the site group (bug 27564) because anons get that too
2703 // and we shouldn't be putting timestamps in Squid-cached HTML
2705 if ( $group === 'user' ) {
2706 // Get the maximum timestamp
2708 foreach ( $grpModules as $module ) {
2709 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2711 // Add a version parameter so cache will break when things change
2712 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2715 $url = ResourceLoader
::makeLoaderURL(
2716 array_keys( $grpModules ),
2717 $this->getLanguage()->getCode(),
2718 $this->getSkin()->getSkinName(),
2721 ResourceLoader
::inDebugMode(),
2722 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2723 $this->isPrintable(),
2724 $this->getRequest()->getBool( 'handheld' ),
2727 if ( $useESI && $wgResourceLoaderUseESI ) {
2728 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2729 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2730 $link = Html
::inlineStyle( $esi );
2732 $link = Html
::inlineScript( $esi );
2735 // Automatically select style/script elements
2736 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2737 $link = Html
::linkedStyle( $url );
2738 } elseif ( $loadCall ) {
2739 $link = Html
::inlineScript(
2740 ResourceLoader
::makeLoaderConditionalScript(
2741 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2745 $link = Html
::linkedScript( $url );
2749 if ( $group == 'noscript' ) {
2750 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2752 $links .= $link . "\n";
2759 * JS stuff to put in the "<head>". This is the startup module, config
2760 * vars and modules marked with position 'top'
2762 * @return String: HTML fragment
2764 function getHeadScripts() {
2765 global $wgResourceLoaderExperimentalAsyncLoading;
2767 // Startup - this will immediately load jquery and mediawiki modules
2768 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2770 // Load config before anything else
2771 $scripts .= Html
::inlineScript(
2772 ResourceLoader
::makeLoaderConditionalScript(
2773 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2777 // Load embeddable private modules before any loader links
2778 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2779 // in mw.loader.implement() calls and deferred until mw.user is available
2780 $embedScripts = array( 'user.options', 'user.tokens' );
2781 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2783 // Script and Messages "only" requests marked for top inclusion
2784 // Messages should go first
2785 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2786 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2788 // Modules requests - let the client calculate dependencies and batch requests as it likes
2789 // Only load modules that have marked themselves for loading at the top
2790 $modules = $this->getModules( true, 'top' );
2792 $scripts .= Html
::inlineScript(
2793 ResourceLoader
::makeLoaderConditionalScript(
2794 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2799 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2800 $scripts .= $this->getScriptsForBottomQueue( true );
2807 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2808 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2809 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2810 * user preferences, site JS and user JS
2812 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2815 function getScriptsForBottomQueue( $inHead ) {
2816 global $wgUseSiteJs, $wgAllowUserJs;
2818 // Script and Messages "only" requests marked for bottom inclusion
2819 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2820 // Messages should go first
2821 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2822 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2823 /* $loadCall = */ $inHead
2825 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2826 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2827 /* $loadCall = */ $inHead
2830 // Modules requests - let the client calculate dependencies and batch requests as it likes
2831 // Only load modules that have marked themselves for loading at the bottom
2832 $modules = $this->getModules( true, 'bottom' );
2834 $scripts .= Html
::inlineScript(
2835 ResourceLoader
::makeLoaderConditionalScript(
2836 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2842 $scripts .= "\n" . $this->mScripts
;
2844 $defaultModules = array();
2846 // Add site JS if enabled
2847 if ( $wgUseSiteJs ) {
2848 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2849 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2851 $defaultModules['site'] = 'loading';
2853 // Site module is empty, save request by marking ready in advance (bug 46857)
2854 $defaultModules['site'] = 'ready';
2857 // Add user JS if enabled
2858 if ( $wgAllowUserJs ) {
2859 if ( $this->getUser()->isLoggedIn() ) {
2860 if ( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2861 # XXX: additional security check/prompt?
2862 // We're on a preview of a JS subpage
2863 // Exclude this page from the user module in case it's in there (bug 26283)
2864 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2865 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2867 // Load the previewed JS
2868 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2869 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2870 // asynchronously and may arrive *after* the inline script here. So the previewed code
2871 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2873 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2874 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2875 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2878 $defaultModules['user'] = 'loading';
2880 // Non-logged-in users have an empty user module.
2881 // Save request by marking ready in advance (bug 46857)
2882 $defaultModules['user'] = 'ready';
2885 // User modules are disabled on this wiki.
2886 // Save request by marking ready in advance (bug 46857)
2887 $defaultModules['user'] = 'ready';
2890 // Group JS is only enabled if site JS is enabled.
2891 if ( $wgUseSiteJs ) {
2892 if ( $this->getUser()->isLoggedIn() ) {
2893 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2894 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2896 $defaultModules['user.groups'] = 'loading';
2898 // Non-logged-in users have no user.groups module.
2899 // Save request by marking ready in advance (bug 46857)
2900 $defaultModules['user.groups'] = 'ready';
2903 // Site (and group JS) disabled
2904 $defaultModules['user.groups'] = 'ready';
2909 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2910 foreach ( $defaultModules as $m => $state ) {
2911 if ( $state == 'loading' ) {
2912 unset( $defaultModules[$m] );
2916 if ( count( $defaultModules ) > 0 ) {
2917 $loaderInit = Html
::inlineScript(
2918 ResourceLoader
::makeLoaderConditionalScript(
2919 ResourceLoader
::makeLoaderStateScript( $defaultModules )
2923 return $loaderInit . $scripts;
2927 * JS stuff to put at the bottom of the "<body>"
2930 function getBottomScripts() {
2931 global $wgResourceLoaderExperimentalAsyncLoading;
2933 // Optimise jQuery ready event cross-browser.
2934 // This also enforces $.isReady to be true at </body> which fixes the
2935 // mw.loader bug in Firefox with using document.write between </body>
2936 // and the DOMContentReady event (bug 47457).
2937 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
2939 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2940 $html .= $this->getScriptsForBottomQueue( false );
2947 * Add one or more variables to be set in mw.config in JavaScript.
2949 * @param $keys {String|Array} Key or array of key/value pairs.
2950 * @param $value {Mixed} [optional] Value of the configuration variable.
2952 public function addJsConfigVars( $keys, $value = null ) {
2953 if ( is_array( $keys ) ) {
2954 foreach ( $keys as $key => $value ) {
2955 $this->mJsConfigVars
[$key] = $value;
2960 $this->mJsConfigVars
[$keys] = $value;
2964 * Get an array containing the variables to be set in mw.config in JavaScript.
2966 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2967 * This is only public until that function is removed. You have been warned.
2969 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2970 * - in other words, page-independent/site-wide variables (without state).
2971 * You will only be adding bloat to the html page and causing page caches to
2972 * have to be purged on configuration changes.
2975 public function getJSVars() {
2980 $canonicalSpecialPageName = false; # bug 21115
2982 $title = $this->getTitle();
2983 $ns = $title->getNamespace();
2984 $canonicalNamespace = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2986 $sk = $this->getSkin();
2987 // Get the relevant title so that AJAX features can use the correct page name
2988 // when making API requests from certain special pages (bug 34972).
2989 $relevantTitle = $sk->getRelevantTitle();
2990 $relevantUser = $sk->getRelevantUser();
2992 if ( $ns == NS_SPECIAL
) {
2993 list( $canonicalSpecialPageName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2994 } elseif ( $this->canUseWikiPage() ) {
2995 $wikiPage = $this->getWikiPage();
2996 $curRevisionId = $wikiPage->getLatest();
2997 $articleId = $wikiPage->getId();
3000 $lang = $title->getPageLanguage();
3002 // Pre-process information
3003 $separatorTransTable = $lang->separatorTransformTable();
3004 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3005 $compactSeparatorTransTable = array(
3006 implode( "\t", array_keys( $separatorTransTable ) ),
3007 implode( "\t", $separatorTransTable ),
3009 $digitTransTable = $lang->digitTransformTable();
3010 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3011 $compactDigitTransTable = array(
3012 implode( "\t", array_keys( $digitTransTable ) ),
3013 implode( "\t", $digitTransTable ),
3016 $user = $this->getUser();
3019 'wgCanonicalNamespace' => $canonicalNamespace,
3020 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3021 'wgNamespaceNumber' => $title->getNamespace(),
3022 'wgPageName' => $title->getPrefixedDBkey(),
3023 'wgTitle' => $title->getText(),
3024 'wgCurRevisionId' => $curRevisionId,
3025 'wgRevisionId' => (int)$this->getRevisionId(),
3026 'wgArticleId' => $articleId,
3027 'wgIsArticle' => $this->isArticle(),
3028 'wgIsRedirect' => $title->isRedirect(),
3029 'wgAction' => Action
::getActionName( $this->getContext() ),
3030 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3031 'wgUserGroups' => $user->getEffectiveGroups(),
3032 'wgCategories' => $this->getCategories(),
3033 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3034 'wgPageContentLanguage' => $lang->getCode(),
3035 'wgPageContentModel' => $title->getContentModel(),
3036 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3037 'wgDigitTransformTable' => $compactDigitTransTable,
3038 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3039 'wgMonthNames' => $lang->getMonthNamesArray(),
3040 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3041 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3043 if ( $user->isLoggedIn() ) {
3044 $vars['wgUserId'] = $user->getId();
3045 $vars['wgUserEditCount'] = $user->getEditCount();
3046 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3047 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3048 // Get the revision ID of the oldest new message on the user's talk
3049 // page. This can be used for constructing new message alerts on
3051 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3053 if ( $wgContLang->hasVariants() ) {
3054 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3056 // Same test as SkinTemplate
3057 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user ) && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3058 foreach ( $title->getRestrictionTypes() as $type ) {
3059 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3061 if ( $title->isMainPage() ) {
3062 $vars['wgIsMainPage'] = true;
3064 if ( $this->mRedirectedFrom
) {
3065 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3067 if ( $relevantUser ) {
3068 $vars['wgRelevantUserName'] = $relevantUser->getName();
3071 // Allow extensions to add their custom variables to the mw.config map.
3072 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3073 // page-dependant but site-wide (without state).
3074 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3075 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3077 // Merge in variables from addJsConfigVars last
3078 return array_merge( $vars, $this->mJsConfigVars
);
3082 * To make it harder for someone to slip a user a fake
3083 * user-JavaScript or user-CSS preview, a random token
3084 * is associated with the login session. If it's not
3085 * passed back with the preview request, we won't render
3090 public function userCanPreview() {
3091 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3092 ||
!$this->getRequest()->wasPosted()
3093 ||
!$this->getUser()->matchEditToken(
3094 $this->getRequest()->getVal( 'wpEditToken' ) )
3098 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3102 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3106 * @return array in format "link name or number => 'link html'".
3108 public function getHeadLinksArray() {
3109 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3110 $wgSitename, $wgVersion,
3111 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3112 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3113 $wgRightsPage, $wgRightsUrl;
3117 $canonicalUrl = $this->mCanonicalUrl
;
3119 $tags['meta-generator'] = Html
::element( 'meta', array(
3120 'name' => 'generator',
3121 'content' => "MediaWiki $wgVersion",
3124 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3125 if ( $p !== 'index,follow' ) {
3126 // http://www.robotstxt.org/wc/meta-user.html
3127 // Only show if it's different from the default robots policy
3128 $tags['meta-robots'] = Html
::element( 'meta', array(
3134 foreach ( $this->mMetatags
as $tag ) {
3135 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3137 $tag[0] = substr( $tag[0], 5 );
3141 $tagName = "meta-{$tag[0]}";
3142 if ( isset( $tags[$tagName] ) ) {
3143 $tagName .= $tag[1];
3145 $tags[$tagName] = Html
::element( 'meta',
3148 'content' => $tag[1]
3153 foreach ( $this->mLinktags
as $tag ) {
3154 $tags[] = Html
::element( 'link', $tag );
3157 # Universal edit button
3158 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3159 $user = $this->getUser();
3160 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3161 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3162 // Original UniversalEditButton
3163 $msg = $this->msg( 'edit' )->text();
3164 $tags['universal-edit-button'] = Html
::element( 'link', array(
3165 'rel' => 'alternate',
3166 'type' => 'application/x-wiki',
3168 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3170 // Alternate edit link
3171 $tags['alternative-edit'] = Html
::element( 'link', array(
3174 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3179 # Generally the order of the favicon and apple-touch-icon links
3180 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3181 # uses whichever one appears later in the HTML source. Make sure
3182 # apple-touch-icon is specified first to avoid this.
3183 if ( $wgAppleTouchIcon !== false ) {
3184 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3187 if ( $wgFavicon !== false ) {
3188 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3191 # OpenSearch description link
3192 $tags['opensearch'] = Html
::element( 'link', array(
3194 'type' => 'application/opensearchdescription+xml',
3195 'href' => wfScript( 'opensearch_desc' ),
3196 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3199 if ( $wgEnableAPI ) {
3200 # Real Simple Discovery link, provides auto-discovery information
3201 # for the MediaWiki API (and potentially additional custom API
3202 # support such as WordPress or Twitter-compatible APIs for a
3203 # blogging extension, etc)
3204 $tags['rsd'] = Html
::element( 'link', array(
3206 'type' => 'application/rsd+xml',
3207 // Output a protocol-relative URL here if $wgServer is protocol-relative
3208 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3209 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3214 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3215 $lang = $this->getTitle()->getPageLanguage();
3216 if ( $lang->hasVariants() ) {
3218 $urlvar = $lang->getURLVariant();
3221 $variants = $lang->getVariants();
3222 foreach ( $variants as $_v ) {
3223 $tags["variant-$_v"] = Html
::element( 'link', array(
3224 'rel' => 'alternate',
3225 'hreflang' => wfBCP47( $_v ),
3226 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3230 $canonicalUrl = $this->getTitle()->getLocalURL();
3237 if ( $wgRightsPage ) {
3238 $copy = Title
::newFromText( $wgRightsPage );
3241 $copyright = $copy->getLocalURL();
3245 if ( !$copyright && $wgRightsUrl ) {
3246 $copyright = $wgRightsUrl;
3250 $tags['copyright'] = Html
::element( 'link', array(
3251 'rel' => 'copyright',
3252 'href' => $copyright )
3258 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3259 # Use the page name for the title. In principle, this could
3260 # lead to issues with having the same name for different feeds
3261 # corresponding to the same page, but we can't avoid that at
3264 $tags[] = $this->feedLink(
3267 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3268 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3272 # Recent changes feed should appear on every page (except recentchanges,
3273 # that would be redundant). Put it after the per-page feed to avoid
3274 # changing existing behavior. It's still available, probably via a
3275 # menu in your browser. Some sites might have a different feed they'd
3276 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3277 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3278 # If so, use it instead.
3279 if ( $wgOverrideSiteFeed ) {
3280 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3281 // Note, this->feedLink escapes the url.
3282 $tags[] = $this->feedLink(
3285 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3288 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3289 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3290 foreach ( $wgAdvertisedFeedTypes as $format ) {
3291 $tags[] = $this->feedLink(
3293 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3294 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3301 global $wgEnableCanonicalServerLink;
3302 if ( $wgEnableCanonicalServerLink ) {
3303 if ( $canonicalUrl !== false ) {
3304 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3306 $reqUrl = $this->getRequest()->getRequestURL();
3307 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3310 if ( $canonicalUrl !== false ) {
3311 $tags[] = Html
::element( 'link', array(
3312 'rel' => 'canonical',
3313 'href' => $canonicalUrl
3321 * @return string HTML tag links to be put in the header.
3323 public function getHeadLinks() {
3324 return implode( "\n", $this->getHeadLinksArray() );
3328 * Generate a "<link rel/>" for a feed.
3330 * @param string $type feed type
3331 * @param string $url URL to the feed
3332 * @param string $text value of the "title" attribute
3333 * @return String: HTML fragment
3335 private function feedLink( $type, $url, $text ) {
3336 return Html
::element( 'link', array(
3337 'rel' => 'alternate',
3338 'type' => "application/$type+xml",
3345 * Add a local or specified stylesheet, with the given media options.
3346 * Meant primarily for internal use...
3348 * @param string $style URL to the file
3349 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3350 * @param string $condition for IE conditional comments, specifying an IE version
3351 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3353 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3355 // Even though we expect the media type to be lowercase, but here we
3356 // force it to lowercase to be safe.
3358 $options['media'] = $media;
3361 $options['condition'] = $condition;
3364 $options['dir'] = $dir;
3366 $this->styles
[$style] = $options;
3370 * Adds inline CSS styles
3371 * @param $style_css Mixed: inline CSS
3372 * @param string $flip Set to 'flip' to flip the CSS if needed
3374 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3375 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3376 # If wanted, and the interface is right-to-left, flip the CSS
3377 $style_css = CSSJanus
::transform( $style_css, true, false );
3379 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3383 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3384 * These will be applied to various media & IE conditionals.
3388 public function buildCssLinks() {
3389 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3391 $this->getSkin()->setupSkinUserCss( $this );
3393 // Add ResourceLoader styles
3394 // Split the styles into four groups
3395 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3396 $otherTags = ''; // Tags to append after the normal <link> tags
3397 $resourceLoader = $this->getResourceLoader();
3399 $moduleStyles = $this->getModuleStyles();
3401 // Per-site custom styles
3402 if ( $wgUseSiteCss ) {
3403 $moduleStyles[] = 'site';
3404 $moduleStyles[] = 'noscript';
3405 if ( $this->getUser()->isLoggedIn() ) {
3406 $moduleStyles[] = 'user.groups';
3410 // Per-user custom styles
3411 if ( $wgAllowUserCss ) {
3412 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3413 // We're on a preview of a CSS subpage
3414 // Exclude this page from the user module in case it's in there (bug 26283)
3415 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3416 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3419 // Load the previewed CSS
3420 // If needed, Janus it first. This is user-supplied CSS, so it's
3421 // assumed to be right for the content language directionality.
3422 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3423 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3424 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3426 $otherTags .= Html
::inlineStyle( $previewedCSS );
3428 // Load the user styles normally
3429 $moduleStyles[] = 'user';
3433 // Per-user preference styles
3434 if ( $wgAllowUserCssPrefs ) {
3435 $moduleStyles[] = 'user.cssprefs';
3438 foreach ( $moduleStyles as $name ) {
3439 $module = $resourceLoader->getModule( $name );
3443 $group = $module->getGroup();
3444 // Modules in groups named "other" or anything different than "user", "site" or "private"
3445 // will be placed in the "other" group
3446 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3449 // We want site, private and user styles to override dynamically added styles from modules, but we want
3450 // dynamically added styles to override statically added styles from other modules. So the order
3451 // has to be other, dynamic, site, private, user
3452 // Add statically added styles for other modules
3453 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3454 // Add normal styles added through addStyle()/addInlineStyle() here
3455 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3456 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3457 // We use a <meta> tag with a made-up name for this because that's valid HTML
3458 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3460 // Add site, private and user styles
3461 // 'private' at present only contains user.options, so put that before 'user'
3462 // Any future private modules will likely have a similar user-specific character
3463 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3464 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3465 ResourceLoaderModule
::TYPE_STYLES
3469 // Add stuff in $otherTags (previewed user CSS if applicable)
3477 public function buildCssLinksArray() {
3480 // Add any extension CSS
3481 foreach ( $this->mExtStyles
as $url ) {
3482 $this->addStyle( $url );
3484 $this->mExtStyles
= array();
3486 foreach ( $this->styles
as $file => $options ) {
3487 $link = $this->styleLink( $file, $options );
3489 $links[$file] = $link;
3496 * Generate \<link\> tags for stylesheets
3498 * @param string $style URL to the file
3499 * @param array $options option, can contain 'condition', 'dir', 'media'
3501 * @return String: HTML fragment
3503 protected function styleLink( $style, $options ) {
3504 if ( isset( $options['dir'] ) ) {
3505 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3510 if ( isset( $options['media'] ) ) {
3511 $media = self
::transformCssMedia( $options['media'] );
3512 if ( is_null( $media ) ) {
3519 if ( substr( $style, 0, 1 ) == '/' ||
3520 substr( $style, 0, 5 ) == 'http:' ||
3521 substr( $style, 0, 6 ) == 'https:' ) {
3524 global $wgStylePath, $wgStyleVersion;
3525 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3528 $link = Html
::linkedStyle( $url, $media );
3530 if ( isset( $options['condition'] ) ) {
3531 $condition = htmlspecialchars( $options['condition'] );
3532 $link = "<!--[if $condition]>$link<![endif]-->";
3538 * Transform "media" attribute based on request parameters
3540 * @param string $media current value of the "media" attribute
3541 * @return String: modified value of the "media" attribute, or null to skip
3544 public static function transformCssMedia( $media ) {
3547 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3548 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3550 // Switch in on-screen display for media testing
3552 'printable' => 'print',
3553 'handheld' => 'handheld',
3555 foreach ( $switches as $switch => $targetMedia ) {
3556 if ( $wgRequest->getBool( $switch ) ) {
3557 if ( $media == $targetMedia ) {
3559 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3560 // This regex will not attempt to understand a comma-separated media_query_list
3562 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3563 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3565 // If it's a print request, we never want any kind of screen stylesheets
3566 // If it's a handheld request (currently the only other choice with a switch),
3567 // we don't want simple 'screen' but we might want screen queries that
3568 // have a max-width or something, so we'll pass all others on and let the
3569 // client do the query.
3570 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3581 * Add a wikitext-formatted message to the output.
3582 * This is equivalent to:
3584 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3586 public function addWikiMsg( /*...*/ ) {
3587 $args = func_get_args();
3588 $name = array_shift( $args );
3589 $this->addWikiMsgArray( $name, $args );
3593 * Add a wikitext-formatted message to the output.
3594 * Like addWikiMsg() except the parameters are taken as an array
3595 * instead of a variable argument list.
3597 * @param $name string
3598 * @param $args array
3600 public function addWikiMsgArray( $name, $args ) {
3601 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3605 * This function takes a number of message/argument specifications, wraps them in
3606 * some overall structure, and then parses the result and adds it to the output.
3608 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3609 * on. The subsequent arguments may either be strings, in which case they are the
3610 * message names, or arrays, in which case the first element is the message name,
3611 * and subsequent elements are the parameters to that message.
3613 * Don't use this for messages that are not in users interface language.
3617 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3621 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3623 * The newline after opening div is needed in some wikitext. See bug 19226.
3625 * @param $wrap string
3627 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3628 $msgSpecs = func_get_args();
3629 array_shift( $msgSpecs );
3630 $msgSpecs = array_values( $msgSpecs );
3632 foreach ( $msgSpecs as $n => $spec ) {
3633 if ( is_array( $spec ) ) {
3635 $name = array_shift( $args );
3636 if ( isset( $args['options'] ) ) {
3637 unset( $args['options'] );
3639 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3647 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3649 $this->addWikiText( $s );
3653 * Include jQuery core. Use this to avoid loading it multiple times
3654 * before we get a usable script loader.
3656 * @param array $modules list of jQuery modules which should be loaded
3657 * @return Array: the list of modules which were not loaded.
3659 * @deprecated since 1.17
3661 public function includeJQuery( $modules = array() ) {
3666 * Enables/disables TOC, doesn't override __NOTOC__
3670 public function enableTOC( $flag = true ) {
3671 $this->mEnableTOC
= $flag;
3678 public function isTOCEnabled() {
3679 return $this->mEnableTOC
;
3683 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3687 public function enableSectionEditLinks( $flag = true ) {
3688 $this->mEnableSectionEditLinks
= $flag;
3695 public function sectionEditLinksEnabled() {
3696 return $this->mEnableSectionEditLinks
;