2 if ( !defined( 'MEDIAWIKI' ) ) {
7 * This class should be covered by a general architecture document which does
8 * not exist as of January 2011. This is one of the Core classes and should
9 * be read at least once by any new developers.
11 * This class is used to prepare the final rendering. A skin is then
12 * applied to the output parameters (links, javascript, html, categories ...).
14 * @todo FIXME: Another class handles sending the whole page to the client.
16 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
21 class OutputPage
extends ContextSource
{
22 /// Should be private. Used with addMeta() which adds <meta>
23 var $mMetatags = array();
25 /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
26 var $mKeywords = array();
28 var $mLinktags = array();
30 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
31 var $mExtStyles = array();
33 /// Should be private - has getter and setter. Contains the HTML title
36 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
40 * Holds the debug lines that will be output as comments in page source if
41 * $wgDebugComments is enabled. See also $wgShowDebug.
42 * TODO: make a getter method for this
44 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
46 /// Should be private. Stores contents of <title> tag
49 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = false;
53 * Should be private. Has get/set methods properly documented.
54 * Stores "article flag" toggle.
56 var $mIsArticleRelated = true;
59 * Should be private. We have to set isPrintable(). Some pages should
60 * never be printed (ex: redirections).
62 var $mPrintable = false;
65 * Should be private. We have set/get/append methods.
67 * Contains the page subtitle. Special pages usually have some links here.
68 * Don't confuse with site subtitle added by skins.
70 private $mSubtitle = array();
76 * mLastModified and mEtag are used for sending cache control.
77 * The whole caching system should probably be moved into its own class.
79 var $mLastModified = '';
82 * Should be private. No getter but used in sendCacheControl();
83 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
84 * as a unique identifier for the content. It is later used by the client
85 * to compare its cached version with the server version. Client sends
86 * headers If-Match and If-None-Match containing its locally cached ETAG value.
88 * To get more information, you will have to look at HTTP/1.1 protocol which
89 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
93 var $mCategoryLinks = array();
94 var $mCategories = array();
96 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
97 var $mLanguageLinks = array();
100 * Should be private. Used for JavaScript (pre resource loader)
101 * We should split js / css.
102 * mScripts content is inserted as is in <head> by Skin. This might contains
103 * either a link to a stylesheet or inline css.
108 * Inline CSS styles. Use addInlineStyle() sparsingly
110 var $mInlineStyles = '';
116 * Used by skin template.
117 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
119 var $mPageLinkTitle = '';
121 /// Array of elements in <head>. Parser might add its own headers!
122 var $mHeadItems = array();
124 // @todo FIXME: Next variables probably comes from the resource loader
125 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
126 var $mResourceLoader;
127 var $mJsConfigVars = array();
129 /** @todo FIXME: Is this still used ?*/
130 var $mInlineMsg = array();
132 var $mTemplateIds = array();
133 var $mImageTimeKeys = array();
135 var $mRedirectCode = '';
137 var $mFeedLinksAppendQuery = null;
139 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
140 # @see ResourceLoaderModule::$origin
141 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
142 protected $mAllowedModules = array(
143 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
147 * @EasterEgg I just love the name for this self documenting variable.
150 var $mDoNothing = false;
153 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
156 * lazy initialised, use parserOptions()
159 protected $mParserOptions = null;
162 * Handles the atom / rss links.
163 * We probably only support atom in 2011.
164 * Looks like a private variable.
165 * @see $wgAdvertisedFeedTypes
167 var $mFeedLinks = array();
169 // Gwicke work on squid caching? Roughly from 2003.
170 var $mEnableClientCache = true;
173 * Flag if output should only contain the body of the article.
176 var $mArticleBodyOnly = false;
178 var $mNewSectionLink = false;
179 var $mHideNewSectionLink = false;
182 * Comes from the parser. This was probably made to load CSS/JS only
183 * if we had <gallery>. Used directly in CategoryPage.php
184 * Looks like resource loader can replace this.
186 var $mNoGallery = false;
188 // should be private.
189 var $mPageTitleActionText = '';
190 var $mParseWarnings = array();
192 // Cache stuff. Looks like mEnableClientCache
193 var $mSquidMaxage = 0;
196 var $mPreventClickjacking = true;
198 /// should be private. To include the variable {{REVISIONID}}
199 var $mRevisionId = null;
200 private $mRevisionTimestamp = null;
202 var $mFileVersion = null;
205 * An array of stylesheet filenames (relative from skins path), with options
206 * for CSS media, IE conditions, and RTL/LTR direction.
207 * For internal use; add settings in the skin via $this->addStyle()
209 * Style again! This seems like a code duplication since we already have
210 * mStyles. This is what makes OpenSource amazing.
212 var $styles = array();
215 * Whether jQuery is already handled.
217 protected $mJQueryDone = false;
219 private $mIndexPolicy = 'index';
220 private $mFollowPolicy = 'follow';
221 private $mVaryHeader = array(
222 'Accept-Encoding' => array( 'list-contains=gzip' ),
227 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
232 private $mRedirectedFrom = null;
235 * Name prefixes that can be used in addMeta
237 public static $metaAttrPrefixes = array(
238 'http' => 'http-equiv',
239 'itemprop' => 'itemprop',
240 'property' => 'property',
244 * Constructor for OutputPage. This should not be called directly.
245 * Instead a new RequestContext should be created and it will implicitly create
246 * a OutputPage tied to that context.
248 function __construct( IContextSource
$context = null ) {
249 if ( $context === null ) {
250 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
251 wfDeprecated( __METHOD__
);
253 $this->setContext( $context );
258 * Redirect to $url rather than displaying the normal page
260 * @param $url String: URL
261 * @param $responsecode String: HTTP status code
263 public function redirect( $url, $responsecode = '302' ) {
264 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
265 $this->mRedirect
= str_replace( "\n", '', $url );
266 $this->mRedirectCode
= $responsecode;
270 * Get the URL to redirect to, or an empty string if not redirect URL set
274 public function getRedirect() {
275 return $this->mRedirect
;
279 * Set the HTTP status code to send with the output.
281 * @param $statusCode Integer
283 public function setStatusCode( $statusCode ) {
284 $this->mStatusCode
= $statusCode;
288 * Add a new <meta> tag
289 * To add an http-equiv meta tag, precede the name with "http:"
290 * To add a Microdata itemprop meta tag, precede the name with "itemprop:"
291 * To add a RDFa property meta tag, precede the name with "property:"
293 * itemprop: and property: were introduced in 1.20, you can feature
294 * test for them by checking for the key in the new
295 * OutputPage::$metaAttrPrefixes variable.
297 * @param $name String tag name
298 * @param $val String tag value
300 function addMeta( $name, $val ) {
301 array_push( $this->mMetatags
, array( $name, $val ) );
305 * Add a keyword or a list of keywords in the page header
307 * @param $text String or array of strings
309 function addKeyword( $text ) {
310 if( is_array( $text ) ) {
311 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
313 array_push( $this->mKeywords
, $text );
318 * Add a new \<link\> tag to the page header
320 * @param $linkarr Array: associative array of attributes.
322 function addLink( $linkarr ) {
323 array_push( $this->mLinktags
, $linkarr );
327 * Add a new \<link\> with "rel" attribute set to "meta"
329 * @param $linkarr Array: associative array mapping attribute names to their
330 * values, both keys and values will be escaped, and the
331 * "rel" attribute will be automatically added
333 function addMetadataLink( $linkarr ) {
334 $linkarr['rel'] = $this->getMetadataAttribute();
335 $this->addLink( $linkarr );
339 * Get the value of the "rel" attribute for metadata links
343 public function getMetadataAttribute() {
344 # note: buggy CC software only reads first "meta" link
345 static $haveMeta = false;
347 return 'alternate meta';
355 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
357 * @param $script String: raw HTML
359 function addScript( $script ) {
360 $this->mScripts
.= $script . "\n";
364 * Register and add a stylesheet from an extension directory.
366 * @param $url String path to sheet. Provide either a full url (beginning
367 * with 'http', etc) or a relative path from the document root
368 * (beginning with '/'). Otherwise it behaves identically to
369 * addStyle() and draws from the /skins folder.
371 public function addExtensionStyle( $url ) {
372 array_push( $this->mExtStyles
, $url );
376 * Get all styles added by extensions
380 function getExtStyle() {
381 return $this->mExtStyles
;
385 * Add a JavaScript file out of skins/common, or a given relative path.
387 * @param $file String: filename in skins/common or complete on-server path
389 * @param $version String: style version of the file. Defaults to $wgStyleVersion
391 public function addScriptFile( $file, $version = null ) {
392 global $wgStylePath, $wgStyleVersion;
393 // See if $file parameter is an absolute URL or begins with a slash
394 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
397 $path = "{$wgStylePath}/common/{$file}";
399 if ( is_null( $version ) )
400 $version = $wgStyleVersion;
401 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
405 * Add a self-contained script tag with the given contents
407 * @param $script String: JavaScript text, no <script> tags
409 public function addInlineScript( $script ) {
410 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
414 * Get all registered JS and CSS tags for the header.
418 function getScript() {
419 return $this->mScripts
. $this->getHeadItems();
423 * Filter an array of modules to remove insufficiently trustworthy members, and modules
424 * which are no longer registered (eg a page is cached before an extension is disabled)
425 * @param $modules Array
426 * @param $position String if not null, only return modules with this position
427 * @param $type string
430 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
431 $resourceLoader = $this->getResourceLoader();
432 $filteredModules = array();
433 foreach( $modules as $val ){
434 $module = $resourceLoader->getModule( $val );
435 if( $module instanceof ResourceLoaderModule
436 && $module->getOrigin() <= $this->getAllowedModules( $type )
437 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
439 $filteredModules[] = $val;
442 return $filteredModules;
446 * Get the list of modules to include on this page
448 * @param $filter Bool whether to filter out insufficiently trustworthy modules
449 * @param $position String if not null, only return modules with this position
450 * @param $param string
451 * @return Array of module names
453 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
454 $modules = array_values( array_unique( $this->$param ) );
456 ?
$this->filterModules( $modules, $position )
461 * Add one or more modules recognized by the resource loader. Modules added
462 * through this function will be loaded by the resource loader when the
465 * @param $modules Mixed: module name (string) or array of module names
467 public function addModules( $modules ) {
468 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
472 * Get the list of module JS to include on this page
477 * @return array of module names
479 public function getModuleScripts( $filter = false, $position = null ) {
480 return $this->getModules( $filter, $position, 'mModuleScripts' );
484 * Add only JS of one or more modules recognized by the resource loader. Module
485 * scripts added through this function will be loaded by the resource loader when
488 * @param $modules Mixed: module name (string) or array of module names
490 public function addModuleScripts( $modules ) {
491 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
495 * Get the list of module CSS to include on this page
500 * @return Array of module names
502 public function getModuleStyles( $filter = false, $position = null ) {
503 return $this->getModules( $filter, $position, 'mModuleStyles' );
507 * Add only CSS of one or more modules recognized by the resource loader. Module
508 * styles added through this function will be loaded by the resource loader when
511 * @param $modules Mixed: module name (string) or array of module names
513 public function addModuleStyles( $modules ) {
514 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
518 * Get the list of module messages to include on this page
523 * @return Array of module names
525 public function getModuleMessages( $filter = false, $position = null ) {
526 return $this->getModules( $filter, $position, 'mModuleMessages' );
530 * Add only messages of one or more modules recognized by the resource loader.
531 * Module messages added through this function will be loaded by the resource
532 * loader when the page loads.
534 * @param $modules Mixed: module name (string) or array of module names
536 public function addModuleMessages( $modules ) {
537 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
541 * Get an array of head items
545 function getHeadItemsArray() {
546 return $this->mHeadItems
;
550 * Get all header items in a string
554 function getHeadItems() {
556 foreach ( $this->mHeadItems
as $item ) {
563 * Add or replace an header item to the output
565 * @param $name String: item name
566 * @param $value String: raw HTML
568 public function addHeadItem( $name, $value ) {
569 $this->mHeadItems
[$name] = $value;
573 * Check if the header item $name is already set
575 * @param $name String: item name
578 public function hasHeadItem( $name ) {
579 return isset( $this->mHeadItems
[$name] );
583 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
585 * @param $tag String: value of "ETag" header
587 function setETag( $tag ) {
592 * Set whether the output should only contain the body of the article,
593 * without any skin, sidebar, etc.
594 * Used e.g. when calling with "action=render".
596 * @param $only Boolean: whether to output only the body of the article
598 public function setArticleBodyOnly( $only ) {
599 $this->mArticleBodyOnly
= $only;
603 * Return whether the output will contain only the body of the article
607 public function getArticleBodyOnly() {
608 return $this->mArticleBodyOnly
;
612 * checkLastModified tells the client to use the client-cached page if
613 * possible. If sucessful, the OutputPage is disabled so that
614 * any future call to OutputPage->output() have no effect.
616 * Side effect: sets mLastModified for Last-Modified header
618 * @param $timestamp string
620 * @return Boolean: true iff cache-ok headers was sent.
622 public function checkLastModified( $timestamp ) {
623 global $wgCachePages, $wgCacheEpoch;
625 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
626 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
629 if( !$wgCachePages ) {
630 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
633 if( $this->getUser()->getOption( 'nocache' ) ) {
634 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
638 $timestamp = wfTimestamp( TS_MW
, $timestamp );
639 $modifiedTimes = array(
640 'page' => $timestamp,
641 'user' => $this->getUser()->getTouched(),
642 'epoch' => $wgCacheEpoch
644 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
646 $maxModified = max( $modifiedTimes );
647 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
649 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
650 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
656 foreach ( $modifiedTimes as $name => $value ) {
657 if ( $info !== '' ) {
660 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
663 # IE sends sizes after the date like this:
664 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
665 # this breaks strtotime().
666 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
668 wfSuppressWarnings(); // E_STRICT system time bitching
669 $clientHeaderTime = strtotime( $clientHeader );
671 if ( !$clientHeaderTime ) {
672 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
675 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
677 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
678 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
679 wfDebug( __METHOD__
. ": effective Last-Modified: " .
680 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
681 if( $clientHeaderTime < $maxModified ) {
682 wfDebug( __METHOD__
. ": STALE, $info\n", false );
687 # Give a 304 response code and disable body output
688 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
689 ini_set( 'zlib.output_compression', 0 );
690 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
691 $this->sendCacheControl();
694 // Don't output a compressed blob when using ob_gzhandler;
695 // it's technically against HTTP spec and seems to confuse
696 // Firefox when the response gets split over two packets.
697 wfClearOutputBuffers();
703 * Override the last modified timestamp
705 * @param $timestamp String: new timestamp, in a format readable by
708 public function setLastModified( $timestamp ) {
709 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
713 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
715 * @param $policy String: the literal string to output as the contents of
716 * the meta tag. Will be parsed according to the spec and output in
720 public function setRobotPolicy( $policy ) {
721 $policy = Article
::formatRobotPolicy( $policy );
723 if( isset( $policy['index'] ) ) {
724 $this->setIndexPolicy( $policy['index'] );
726 if( isset( $policy['follow'] ) ) {
727 $this->setFollowPolicy( $policy['follow'] );
732 * Set the index policy for the page, but leave the follow policy un-
735 * @param $policy string Either 'index' or 'noindex'.
738 public function setIndexPolicy( $policy ) {
739 $policy = trim( $policy );
740 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
741 $this->mIndexPolicy
= $policy;
746 * Set the follow policy for the page, but leave the index policy un-
749 * @param $policy String: either 'follow' or 'nofollow'.
752 public function setFollowPolicy( $policy ) {
753 $policy = trim( $policy );
754 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
755 $this->mFollowPolicy
= $policy;
760 * Set the new value of the "action text", this will be added to the
761 * "HTML title", separated from it with " - ".
763 * @param $text String: new value of the "action text"
765 public function setPageTitleActionText( $text ) {
766 $this->mPageTitleActionText
= $text;
770 * Get the value of the "action text"
774 public function getPageTitleActionText() {
775 if ( isset( $this->mPageTitleActionText
) ) {
776 return $this->mPageTitleActionText
;
781 * "HTML title" means the contents of <title>.
782 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
784 * @param $name string
786 public function setHTMLTitle( $name ) {
787 if ( $name instanceof Message
) {
788 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
790 $this->mHTMLtitle
= $name;
795 * Return the "HTML title", i.e. the content of the <title> tag.
799 public function getHTMLTitle() {
800 return $this->mHTMLtitle
;
804 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
808 public function setRedirectedFrom( $t ) {
809 $this->mRedirectedFrom
= $t;
813 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
814 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
815 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
816 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
818 * @param $name string|Message
820 public function setPageTitle( $name ) {
821 if ( $name instanceof Message
) {
822 $name = $name->setContext( $this->getContext() )->text();
825 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
826 # but leave "<i>foobar</i>" alone
827 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
828 $this->mPagetitle
= $nameWithTags;
830 # change "<i>foo&bar</i>" to "foo&bar"
831 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
835 * Return the "page title", i.e. the content of the \<h1\> tag.
839 public function getPageTitle() {
840 return $this->mPagetitle
;
844 * Set the Title object to use
846 * @param $t Title object
848 public function setTitle( Title
$t ) {
849 $this->getContext()->setTitle( $t );
854 * Replace the subtile with $str
856 * @param $str String|Message: new value of the subtitle
858 public function setSubtitle( $str ) {
859 $this->clearSubtitle();
860 $this->addSubtitle( $str );
864 * Add $str to the subtitle
866 * @deprecated in 1.19; use addSubtitle() instead
867 * @param $str String|Message to add to the subtitle
869 public function appendSubtitle( $str ) {
870 $this->addSubtitle( $str );
874 * Add $str to the subtitle
876 * @param $str String|Message to add to the subtitle
878 public function addSubtitle( $str ) {
879 if ( $str instanceof Message
) {
880 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
882 $this->mSubtitle
[] = $str;
887 * Add a subtitle containing a backlink to a page
889 * @param $title Title to link to
891 public function addBacklinkSubtitle( Title
$title ) {
893 if ( $title->isRedirect() ) {
894 $query['redirect'] = 'no';
896 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
900 * Clear the subtitles
902 public function clearSubtitle() {
903 $this->mSubtitle
= array();
911 public function getSubtitle() {
912 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
916 * Set the page as printable, i.e. it'll be displayed with with all
917 * print styles included
919 public function setPrintable() {
920 $this->mPrintable
= true;
924 * Return whether the page is "printable"
928 public function isPrintable() {
929 return $this->mPrintable
;
933 * Disable output completely, i.e. calling output() will have no effect
935 public function disable() {
936 $this->mDoNothing
= true;
940 * Return whether the output will be completely disabled
944 public function isDisabled() {
945 return $this->mDoNothing
;
949 * Show an "add new section" link?
953 public function showNewSectionLink() {
954 return $this->mNewSectionLink
;
958 * Forcibly hide the new section link?
962 public function forceHideNewSectionLink() {
963 return $this->mHideNewSectionLink
;
967 * Add or remove feed links in the page header
968 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
969 * for the new version
972 * @param $show Boolean: true: add default feeds, false: remove all feeds
974 public function setSyndicated( $show = true ) {
976 $this->setFeedAppendQuery( false );
978 $this->mFeedLinks
= array();
983 * Add default feeds to the page header
984 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
985 * for the new version
988 * @param $val String: query to append to feed links or false to output
991 public function setFeedAppendQuery( $val ) {
992 global $wgAdvertisedFeedTypes;
994 $this->mFeedLinks
= array();
996 foreach ( $wgAdvertisedFeedTypes as $type ) {
997 $query = "feed=$type";
998 if ( is_string( $val ) ) {
999 $query .= '&' . $val;
1001 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1006 * Add a feed link to the page header
1008 * @param $format String: feed type, should be a key of $wgFeedClasses
1009 * @param $href String: URL
1011 public function addFeedLink( $format, $href ) {
1012 global $wgAdvertisedFeedTypes;
1014 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1015 $this->mFeedLinks
[$format] = $href;
1020 * Should we output feed links for this page?
1023 public function isSyndicated() {
1024 return count( $this->mFeedLinks
) > 0;
1028 * Return URLs for each supported syndication format for this page.
1029 * @return array associating format keys with URLs
1031 public function getSyndicationLinks() {
1032 return $this->mFeedLinks
;
1036 * Will currently always return null
1040 public function getFeedAppendQuery() {
1041 return $this->mFeedLinksAppendQuery
;
1045 * Set whether the displayed content is related to the source of the
1046 * corresponding article on the wiki
1047 * Setting true will cause the change "article related" toggle to true
1051 public function setArticleFlag( $v ) {
1052 $this->mIsarticle
= $v;
1054 $this->mIsArticleRelated
= $v;
1059 * Return whether the content displayed page is related to the source of
1060 * the corresponding article on the wiki
1064 public function isArticle() {
1065 return $this->mIsarticle
;
1069 * Set whether this page is related an article on the wiki
1070 * Setting false will cause the change of "article flag" toggle to false
1074 public function setArticleRelated( $v ) {
1075 $this->mIsArticleRelated
= $v;
1077 $this->mIsarticle
= false;
1082 * Return whether this page is related an article on the wiki
1086 public function isArticleRelated() {
1087 return $this->mIsArticleRelated
;
1091 * Add new language links
1093 * @param $newLinkArray array Associative array mapping language code to the page
1096 public function addLanguageLinks( $newLinkArray ) {
1097 $this->mLanguageLinks +
= $newLinkArray;
1101 * Reset the language links and add new language links
1103 * @param $newLinkArray array Associative array mapping language code to the page
1106 public function setLanguageLinks( $newLinkArray ) {
1107 $this->mLanguageLinks
= $newLinkArray;
1111 * Get the list of language links
1113 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1115 public function getLanguageLinks() {
1116 return $this->mLanguageLinks
;
1120 * Add an array of categories, with names in the keys
1122 * @param $categories Array mapping category name => sort key
1124 public function addCategoryLinks( $categories ) {
1127 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1131 # Add the links to a LinkBatch
1132 $arr = array( NS_CATEGORY
=> $categories );
1133 $lb = new LinkBatch
;
1134 $lb->setArray( $arr );
1136 # Fetch existence plus the hiddencat property
1137 $dbr = wfGetDB( DB_SLAVE
);
1138 $res = $dbr->select( array( 'page', 'page_props' ),
1139 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1140 $lb->constructSet( 'page', $dbr ),
1143 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1146 # Add the results to the link cache
1147 $lb->addResultToCache( LinkCache
::singleton(), $res );
1149 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1150 $categories = array_combine(
1151 array_keys( $categories ),
1152 array_fill( 0, count( $categories ), 'normal' )
1155 # Mark hidden categories
1156 foreach ( $res as $row ) {
1157 if ( isset( $row->pp_value
) ) {
1158 $categories[$row->page_title
] = 'hidden';
1162 # Add the remaining categories to the skin
1163 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1164 foreach ( $categories as $category => $type ) {
1165 $origcategory = $category;
1166 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1167 $wgContLang->findVariantLink( $category, $title, true );
1168 if ( $category != $origcategory ) {
1169 if ( array_key_exists( $category, $categories ) ) {
1173 $text = $wgContLang->convertHtml( $title->getText() );
1174 $this->mCategories
[] = $title->getText();
1175 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1181 * Reset the category links (but not the category list) and add $categories
1183 * @param $categories Array mapping category name => sort key
1185 public function setCategoryLinks( $categories ) {
1186 $this->mCategoryLinks
= array();
1187 $this->addCategoryLinks( $categories );
1191 * Get the list of category links, in a 2-D array with the following format:
1192 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1193 * hidden categories) and $link a HTML fragment with a link to the category
1198 public function getCategoryLinks() {
1199 return $this->mCategoryLinks
;
1203 * Get the list of category names this page belongs to
1205 * @return Array of strings
1207 public function getCategories() {
1208 return $this->mCategories
;
1212 * Do not allow scripts which can be modified by wiki users to load on this page;
1213 * only allow scripts bundled with, or generated by, the software.
1215 public function disallowUserJs() {
1216 $this->reduceAllowedModules(
1217 ResourceLoaderModule
::TYPE_SCRIPTS
,
1218 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1223 * Return whether user JavaScript is allowed for this page
1224 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1225 * trustworthiness is identified and enforced automagically.
1226 * Will be removed in 1.20.
1229 public function isUserJsAllowed() {
1230 wfDeprecated( __METHOD__
, '1.18' );
1231 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1235 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1236 * @see ResourceLoaderModule::$origin
1237 * @param $type String ResourceLoaderModule TYPE_ constant
1238 * @return Int ResourceLoaderModule ORIGIN_ class constant
1240 public function getAllowedModules( $type ){
1241 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1242 return min( array_values( $this->mAllowedModules
) );
1244 return isset( $this->mAllowedModules
[$type] )
1245 ?
$this->mAllowedModules
[$type]
1246 : ResourceLoaderModule
::ORIGIN_ALL
;
1251 * Set the highest level of CSS/JS untrustworthiness allowed
1252 * @param $type String ResourceLoaderModule TYPE_ constant
1253 * @param $level Int ResourceLoaderModule class constant
1255 public function setAllowedModules( $type, $level ){
1256 $this->mAllowedModules
[$type] = $level;
1260 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1261 * @param $type String
1262 * @param $level Int ResourceLoaderModule class constant
1264 public function reduceAllowedModules( $type, $level ){
1265 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1269 * Prepend $text to the body HTML
1271 * @param $text String: HTML
1273 public function prependHTML( $text ) {
1274 $this->mBodytext
= $text . $this->mBodytext
;
1278 * Append $text to the body HTML
1280 * @param $text String: HTML
1282 public function addHTML( $text ) {
1283 $this->mBodytext
.= $text;
1287 * Shortcut for adding an Html::element via addHTML.
1291 * @param $element string
1292 * @param $attribs array
1293 * @param $contents string
1295 public function addElement( $element, $attribs = array(), $contents = '' ) {
1296 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1300 * Clear the body HTML
1302 public function clearHTML() {
1303 $this->mBodytext
= '';
1309 * @return String: HTML
1311 public function getHTML() {
1312 return $this->mBodytext
;
1316 * Add $text to the debug output
1318 * @param $text String: debug text
1320 public function debug( $text ) {
1321 $this->mDebugtext
.= $text;
1325 * Get/set the ParserOptions object to use for wikitext parsing
1327 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1328 * current ParserOption object
1329 * @return ParserOptions object
1331 public function parserOptions( $options = null ) {
1332 if ( !$this->mParserOptions
) {
1333 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1334 $this->mParserOptions
->setEditSection( false );
1336 return wfSetVar( $this->mParserOptions
, $options );
1340 * Set the revision ID which will be seen by the wiki text parser
1341 * for things such as embedded {{REVISIONID}} variable use.
1343 * @param $revid Mixed: an positive integer, or null
1344 * @return Mixed: previous value
1346 public function setRevisionId( $revid ) {
1347 $val = is_null( $revid ) ?
null : intval( $revid );
1348 return wfSetVar( $this->mRevisionId
, $val );
1352 * Get the displayed revision ID
1356 public function getRevisionId() {
1357 return $this->mRevisionId
;
1361 * Set the timestamp of the revision which will be displayed. This is used
1362 * to avoid a extra DB call in Skin::lastModified().
1364 * @param $revid Mixed: string, or null
1365 * @return Mixed: previous value
1367 public function setRevisionTimestamp( $timestmap ) {
1368 return wfSetVar( $this->mRevisionTimestamp
, $timestmap );
1372 * Get the timestamp of displayed revision.
1373 * This will be null if not filled by setRevisionTimestamp().
1375 * @return String or null
1377 public function getRevisionTimestamp() {
1378 return $this->mRevisionTimestamp
;
1382 * Set the displayed file version
1384 * @param $file File|bool
1385 * @return Mixed: previous value
1387 public function setFileVersion( $file ) {
1389 if ( $file instanceof File
&& $file->exists() ) {
1390 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1392 return wfSetVar( $this->mFileVersion
, $val, true );
1396 * Get the displayed file version
1398 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1400 public function getFileVersion() {
1401 return $this->mFileVersion
;
1405 * Get the templates used on this page
1407 * @return Array (namespace => dbKey => revId)
1410 public function getTemplateIds() {
1411 return $this->mTemplateIds
;
1415 * Get the files used on this page
1417 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1420 public function getFileSearchOptions() {
1421 return $this->mImageTimeKeys
;
1425 * Convert wikitext to HTML and add it to the buffer
1426 * Default assumes that the current page title will be used.
1428 * @param $text String
1429 * @param $linestart Boolean: is this the start of a line?
1430 * @param $interface Boolean: is this text in the user interface language?
1432 public function addWikiText( $text, $linestart = true, $interface = true ) {
1433 $title = $this->getTitle(); // Work arround E_STRICT
1434 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1438 * Add wikitext with a custom Title object
1440 * @param $text String: wikitext
1441 * @param $title Title object
1442 * @param $linestart Boolean: is this the start of a line?
1444 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1445 $this->addWikiTextTitle( $text, $title, $linestart );
1449 * Add wikitext with a custom Title object and tidy enabled.
1451 * @param $text String: wikitext
1452 * @param $title Title object
1453 * @param $linestart Boolean: is this the start of a line?
1455 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1456 $this->addWikiTextTitle( $text, $title, $linestart, true );
1460 * Add wikitext with tidy enabled
1462 * @param $text String: wikitext
1463 * @param $linestart Boolean: is this the start of a line?
1465 public function addWikiTextTidy( $text, $linestart = true ) {
1466 $title = $this->getTitle();
1467 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1471 * Add wikitext with a custom Title object
1473 * @param $text String: wikitext
1474 * @param $title Title object
1475 * @param $linestart Boolean: is this the start of a line?
1476 * @param $tidy Boolean: whether to use tidy
1477 * @param $interface Boolean: whether it is an interface message
1478 * (for example disables conversion)
1480 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1483 wfProfileIn( __METHOD__
);
1485 $popts = $this->parserOptions();
1486 $oldTidy = $popts->setTidy( $tidy );
1487 $popts->setInterfaceMessage( (bool) $interface );
1489 $parserOutput = $wgParser->parse(
1490 $text, $title, $popts,
1491 $linestart, true, $this->mRevisionId
1494 $popts->setTidy( $oldTidy );
1496 $this->addParserOutput( $parserOutput );
1498 wfProfileOut( __METHOD__
);
1502 * Add a ParserOutput object, but without Html
1504 * @param $parserOutput ParserOutput object
1506 public function addParserOutputNoText( &$parserOutput ) {
1507 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1508 $this->addCategoryLinks( $parserOutput->getCategories() );
1509 $this->mNewSectionLink
= $parserOutput->getNewSection();
1510 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1512 $this->mParseWarnings
= $parserOutput->getWarnings();
1513 if ( !$parserOutput->isCacheable() ) {
1514 $this->enableClientCache( false );
1516 $this->mNoGallery
= $parserOutput->getNoGallery();
1517 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1518 $this->addModules( $parserOutput->getModules() );
1519 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1520 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1521 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1523 // Template versioning...
1524 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1525 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1526 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1528 $this->mTemplateIds
[$ns] = $dbks;
1531 // File versioning...
1532 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1533 $this->mImageTimeKeys
[$dbk] = $data;
1536 // Hooks registered in the object
1537 global $wgParserOutputHooks;
1538 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1539 list( $hookName, $data ) = $hookInfo;
1540 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1541 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1545 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1549 * Add a ParserOutput object
1551 * @param $parserOutput ParserOutput
1553 function addParserOutput( &$parserOutput ) {
1554 $this->addParserOutputNoText( $parserOutput );
1555 $text = $parserOutput->getText();
1556 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1557 $this->addHTML( $text );
1562 * Add the output of a QuickTemplate to the output buffer
1564 * @param $template QuickTemplate
1566 public function addTemplate( &$template ) {
1568 $template->execute();
1569 $this->addHTML( ob_get_contents() );
1574 * Parse wikitext and return the HTML.
1576 * @param $text String
1577 * @param $linestart Boolean: is this the start of a line?
1578 * @param $interface Boolean: use interface language ($wgLang instead of
1579 * $wgContLang) while parsing language sensitive magic
1580 * words like GRAMMAR and PLURAL. This also disables
1581 * LanguageConverter.
1582 * @param $language Language object: target language object, will override
1584 * @return String: HTML
1586 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1589 if( is_null( $this->getTitle() ) ) {
1590 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1593 $popts = $this->parserOptions();
1595 $popts->setInterfaceMessage( true );
1597 if ( $language !== null ) {
1598 $oldLang = $popts->setTargetLanguage( $language );
1601 $parserOutput = $wgParser->parse(
1602 $text, $this->getTitle(), $popts,
1603 $linestart, true, $this->mRevisionId
1607 $popts->setInterfaceMessage( false );
1609 if ( $language !== null ) {
1610 $popts->setTargetLanguage( $oldLang );
1613 return $parserOutput->getText();
1617 * Parse wikitext, strip paragraphs, and return the HTML.
1619 * @param $text String
1620 * @param $linestart Boolean: is this the start of a line?
1621 * @param $interface Boolean: use interface language ($wgLang instead of
1622 * $wgContLang) while parsing language sensitive magic
1623 * words like GRAMMAR and PLURAL
1624 * @return String: HTML
1626 public function parseInline( $text, $linestart = true, $interface = false ) {
1627 $parsed = $this->parse( $text, $linestart, $interface );
1630 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1638 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1640 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1642 public function setSquidMaxage( $maxage ) {
1643 $this->mSquidMaxage
= $maxage;
1647 * Use enableClientCache(false) to force it to send nocache headers
1649 * @param $state bool
1653 public function enableClientCache( $state ) {
1654 return wfSetVar( $this->mEnableClientCache
, $state );
1658 * Get the list of cookies that will influence on the cache
1662 function getCacheVaryCookies() {
1663 global $wgCookiePrefix, $wgCacheVaryCookies;
1665 if ( $cookies === null ) {
1666 $cookies = array_merge(
1668 "{$wgCookiePrefix}Token",
1669 "{$wgCookiePrefix}LoggedOut",
1674 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1680 * Return whether this page is not cacheable because "useskin" or "uselang"
1681 * URL parameters were passed.
1685 function uncacheableBecauseRequestVars() {
1686 $request = $this->getRequest();
1687 return $request->getText( 'useskin', false ) === false
1688 && $request->getText( 'uselang', false ) === false;
1692 * Check if the request has a cache-varying cookie header
1693 * If it does, it's very important that we don't allow public caching
1697 function haveCacheVaryCookies() {
1698 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1699 if ( $cookieHeader === false ) {
1702 $cvCookies = $this->getCacheVaryCookies();
1703 foreach ( $cvCookies as $cookieName ) {
1704 # Check for a simple string match, like the way squid does it
1705 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1706 wfDebug( __METHOD__
. ": found $cookieName\n" );
1710 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1715 * Add an HTTP header that will influence on the cache
1717 * @param $header String: header name
1718 * @param $option Array|null
1719 * @todo FIXME: Document the $option parameter; it appears to be for
1720 * X-Vary-Options but what format is acceptable?
1722 public function addVaryHeader( $header, $option = null ) {
1723 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1724 $this->mVaryHeader
[$header] = (array)$option;
1725 } elseif( is_array( $option ) ) {
1726 if( is_array( $this->mVaryHeader
[$header] ) ) {
1727 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1729 $this->mVaryHeader
[$header] = $option;
1732 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1736 * Get a complete X-Vary-Options header
1740 public function getXVO() {
1741 $cvCookies = $this->getCacheVaryCookies();
1743 $cookiesOption = array();
1744 foreach ( $cvCookies as $cookieName ) {
1745 $cookiesOption[] = 'string-contains=' . $cookieName;
1747 $this->addVaryHeader( 'Cookie', $cookiesOption );
1750 foreach( $this->mVaryHeader
as $header => $option ) {
1751 $newheader = $header;
1752 if( is_array( $option ) ) {
1753 $newheader .= ';' . implode( ';', $option );
1755 $headers[] = $newheader;
1757 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1763 * bug 21672: Add Accept-Language to Vary and XVO headers
1764 * if there's no 'variant' parameter existed in GET.
1767 * /w/index.php?title=Main_page should always be served; but
1768 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1770 function addAcceptLanguage() {
1771 $lang = $this->getTitle()->getPageLanguage();
1772 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1773 $variants = $lang->getVariants();
1774 $aloption = array();
1775 foreach ( $variants as $variant ) {
1776 if( $variant === $lang->getCode() ) {
1779 $aloption[] = 'string-contains=' . $variant;
1781 // IE and some other browsers use another form of language code
1782 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1783 // We should handle these too.
1784 $ievariant = explode( '-', $variant );
1785 if ( count( $ievariant ) == 2 ) {
1786 $ievariant[1] = strtoupper( $ievariant[1] );
1787 $ievariant = implode( '-', $ievariant );
1788 $aloption[] = 'string-contains=' . $ievariant;
1792 $this->addVaryHeader( 'Accept-Language', $aloption );
1797 * Set a flag which will cause an X-Frame-Options header appropriate for
1798 * edit pages to be sent. The header value is controlled by
1799 * $wgEditPageFrameOptions.
1801 * This is the default for special pages. If you display a CSRF-protected
1802 * form on an ordinary view page, then you need to call this function.
1804 * @param $enable bool
1806 public function preventClickjacking( $enable = true ) {
1807 $this->mPreventClickjacking
= $enable;
1811 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1812 * This can be called from pages which do not contain any CSRF-protected
1815 public function allowClickjacking() {
1816 $this->mPreventClickjacking
= false;
1820 * Get the X-Frame-Options header value (without the name part), or false
1821 * if there isn't one. This is used by Skin to determine whether to enable
1822 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1826 public function getFrameOptions() {
1827 global $wgBreakFrames, $wgEditPageFrameOptions;
1828 if ( $wgBreakFrames ) {
1830 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1831 return $wgEditPageFrameOptions;
1837 * Send cache control HTTP headers
1839 public function sendCacheControl() {
1840 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1842 $response = $this->getRequest()->response();
1843 if ( $wgUseETag && $this->mETag
) {
1844 $response->header( "ETag: $this->mETag" );
1847 $this->addAcceptLanguage();
1849 # don't serve compressed data to clients who can't handle it
1850 # maintain different caches for logged-in users and non-logged in ones
1851 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1854 # Add an X-Vary-Options header for Squid with Wikimedia patches
1855 $response->header( $this->getXVO() );
1858 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1860 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1861 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1865 # We'll purge the proxy cache explicitly, but require end user agents
1866 # to revalidate against the proxy on each visit.
1867 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1868 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1869 # start with a shorter timeout for initial testing
1870 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1871 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1872 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1874 # We'll purge the proxy cache for anons explicitly, but require end user agents
1875 # to revalidate against the proxy on each visit.
1876 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1877 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1878 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1879 # start with a shorter timeout for initial testing
1880 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1881 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1884 # We do want clients to cache if they can, but they *must* check for updates
1885 # on revisiting the page.
1886 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1887 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1888 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1890 if($this->mLastModified
) {
1891 $response->header( "Last-Modified: {$this->mLastModified}" );
1894 wfDebug( __METHOD__
. ": no caching **\n", false );
1896 # In general, the absence of a last modified header should be enough to prevent
1897 # the client from using its cache. We send a few other things just to make sure.
1898 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1899 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1900 $response->header( 'Pragma: no-cache' );
1905 * Get the message associed with the HTTP response code $code
1907 * @param $code Integer: status code
1908 * @return String or null: message or null if $code is not in the list of
1911 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1913 public static function getStatusMessage( $code ) {
1914 wfDeprecated( __METHOD__
);
1915 return HttpStatus
::getMessage( $code );
1919 * Finally, all the text has been munged and accumulated into
1920 * the object, let's actually output it:
1922 public function output() {
1923 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1925 if( $this->mDoNothing
) {
1929 wfProfileIn( __METHOD__
);
1931 $response = $this->getRequest()->response();
1933 if ( $this->mRedirect
!= '' ) {
1934 # Standards require redirect URLs to be absolute
1935 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1937 $redirect = $this->mRedirect
;
1938 $code = $this->mRedirectCode
;
1940 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1941 if( $code == '301' ||
$code == '303' ) {
1942 if( !$wgDebugRedirects ) {
1943 $message = HttpStatus
::getMessage( $code );
1944 $response->header( "HTTP/1.1 $code $message" );
1946 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1948 if ( $wgVaryOnXFP ) {
1949 $this->addVaryHeader( 'X-Forwarded-Proto' );
1951 $this->sendCacheControl();
1953 $response->header( "Content-Type: text/html; charset=utf-8" );
1954 if( $wgDebugRedirects ) {
1955 $url = htmlspecialchars( $redirect );
1956 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1957 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1958 print "</body>\n</html>\n";
1960 $response->header( 'Location: ' . $redirect );
1964 wfProfileOut( __METHOD__
);
1966 } elseif ( $this->mStatusCode
) {
1967 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1969 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1973 # Buffer output; final headers may depend on later processing
1976 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1977 $response->header( 'Content-language: ' . $wgLanguageCode );
1979 // Prevent framing, if requested
1980 $frameOptions = $this->getFrameOptions();
1981 if ( $frameOptions ) {
1982 $response->header( "X-Frame-Options: $frameOptions" );
1985 if ( $this->mArticleBodyOnly
) {
1986 $this->out( $this->mBodytext
);
1988 $this->addDefaultModules();
1990 $sk = $this->getSkin();
1992 // Hook that allows last minute changes to the output page, e.g.
1993 // adding of CSS or Javascript by extensions.
1994 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1996 wfProfileIn( 'Output-skin' );
1998 wfProfileOut( 'Output-skin' );
2001 $this->sendCacheControl();
2003 wfProfileOut( __METHOD__
);
2007 * Actually output something with print().
2009 * @param $ins String: the string to output
2011 public function out( $ins ) {
2016 * Produce a "user is blocked" page.
2017 * @deprecated since 1.18
2019 function blockedPage() {
2020 throw new UserBlockedError( $this->getUser()->mBlock
);
2024 * Prepare this object to display an error page; disable caching and
2025 * indexing, clear the current text and redirect, set the page's title
2026 * and optionally an custom HTML title (content of the <title> tag).
2028 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2029 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2030 * optional, if not passed the <title> attribute will be
2031 * based on $pageTitle
2033 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2034 if ( $this->getTitle() ) {
2035 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
2038 $this->setPageTitle( $pageTitle );
2039 if ( $htmlTitle !== false ) {
2040 $this->setHTMLTitle( $htmlTitle );
2042 $this->setRobotPolicy( 'noindex,nofollow' );
2043 $this->setArticleRelated( false );
2044 $this->enableClientCache( false );
2045 $this->mRedirect
= '';
2046 $this->clearSubtitle();
2051 * Output a standard error page
2053 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2054 * showErrorPage( 'titlemsg', $messageObject );
2056 * @param $title String: message key for page title
2057 * @param $msg Mixed: message key (string) for page text, or a Message object
2058 * @param $params Array: message parameters; ignored if $msg is a Message object
2060 public function showErrorPage( $title, $msg, $params = array() ) {
2061 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2063 if ( $msg instanceof Message
){
2064 $this->addHTML( $msg->parse() );
2066 $this->addWikiMsgArray( $msg, $params );
2069 $this->returnToMain();
2073 * Output a standard permission error page
2075 * @param $errors Array: error message keys
2076 * @param $action String: action that was denied or null if unknown
2078 public function showPermissionsErrorPage( $errors, $action = null ) {
2079 global $wgGroupPermissions;
2081 // For some action (read, edit, create and upload), display a "login to do this action"
2082 // error if all of the following conditions are met:
2083 // 1. the user is not logged in
2084 // 2. the only error is insufficient permissions (i.e. no block or something else)
2085 // 3. the error can be avoided simply by logging in
2086 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2087 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2088 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2089 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2090 ||
( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2092 $displayReturnto = null;
2094 # Due to bug 32276, if a user does not have read permissions,
2095 # $this->getTitle() will just give Special:Badtitle, which is
2096 # not especially useful as a returnto parameter. Use the title
2097 # from the request instead, if there was one.
2098 $request = $this->getRequest();
2099 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2100 if ( $action == 'edit' ) {
2101 $msg = 'whitelistedittext';
2102 $displayReturnto = $returnto;
2103 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2104 $msg = 'nocreatetext';
2105 } elseif ( $action == 'upload' ) {
2106 $msg = 'uploadnologintext';
2108 $msg = 'loginreqpagetext';
2109 $displayReturnto = Title
::newMainPage();
2115 $query['returnto'] = $returnto->getPrefixedText();
2117 if ( !$request->wasPosted() ) {
2118 $returntoquery = $request->getValues();
2119 unset( $returntoquery['title'] );
2120 unset( $returntoquery['returnto'] );
2121 unset( $returntoquery['returntoquery'] );
2122 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2125 $loginLink = Linker
::linkKnown(
2126 SpecialPage
::getTitleFor( 'Userlogin' ),
2127 $this->msg( 'loginreqlink' )->escaped(),
2132 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2133 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2135 # Don't return to a page the user can't read otherwise
2136 # we'll end up in a pointless loop
2137 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2138 $this->returnToMain( null, $displayReturnto );
2141 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2142 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2147 * Display an error page indicating that a given version of MediaWiki is
2148 * required to use it
2150 * @param $version Mixed: the version of MediaWiki needed to use the page
2152 public function versionRequired( $version ) {
2153 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2155 $this->addWikiMsg( 'versionrequiredtext', $version );
2156 $this->returnToMain();
2160 * Display an error page noting that a given permission bit is required.
2161 * @deprecated since 1.18, just throw the exception directly
2162 * @param $permission String: key required
2164 public function permissionRequired( $permission ) {
2165 throw new PermissionsError( $permission );
2169 * Produce the stock "please login to use the wiki" page
2171 * @deprecated in 1.19; throw the exception directly
2173 public function loginToUse() {
2174 throw new PermissionsError( 'read' );
2178 * Format a list of error messages
2180 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2181 * @param $action String: action that was denied or null if unknown
2182 * @return String: the wikitext error-messages, formatted into a list.
2184 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2185 if ( $action == null ) {
2186 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2188 $action_desc = $this->msg( "action-$action" )->plain();
2190 'permissionserrorstext-withaction',
2193 )->plain() . "\n\n";
2196 if ( count( $errors ) > 1 ) {
2197 $text .= '<ul class="permissions-errors">' . "\n";
2199 foreach( $errors as $error ) {
2201 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2206 $text .= "<div class=\"permissions-errors\">\n" .
2207 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2215 * Display a page stating that the Wiki is in read-only mode,
2216 * and optionally show the source of the page that the user
2217 * was trying to edit. Should only be called (for this
2218 * purpose) after wfReadOnly() has returned true.
2220 * For historical reasons, this function is _also_ used to
2221 * show the error message when a user tries to edit a page
2222 * they are not allowed to edit. (Unless it's because they're
2223 * blocked, then we show blockedPage() instead.) In this
2224 * case, the second parameter should be set to true and a list
2225 * of reasons supplied as the third parameter.
2227 * @todo Needs to be split into multiple functions.
2229 * @param $source String: source code to show (or null).
2230 * @param $protected Boolean: is this a permissions error?
2231 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2232 * @param $action String: action that was denied or null if unknown
2234 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2235 $this->setRobotPolicy( 'noindex,nofollow' );
2236 $this->setArticleRelated( false );
2238 // If no reason is given, just supply a default "I can't let you do
2239 // that, Dave" message. Should only occur if called by legacy code.
2240 if ( $protected && empty( $reasons ) ) {
2241 $reasons[] = array( 'badaccess-group0' );
2244 if ( !empty( $reasons ) ) {
2245 // Permissions error
2247 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2248 $this->addBacklinkSubtitle( $this->getTitle() );
2250 $this->setPageTitle( $this->msg( 'badaccess' ) );
2252 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2254 // Wiki is read only
2255 throw new ReadOnlyError
;
2258 // Show source, if supplied
2259 if( is_string( $source ) ) {
2260 $this->addWikiMsg( 'viewsourcetext' );
2262 $pageLang = $this->getTitle()->getPageLanguage();
2264 'id' => 'wpTextbox1',
2265 'name' => 'wpTextbox1',
2266 'cols' => $this->getUser()->getOption( 'cols' ),
2267 'rows' => $this->getUser()->getOption( 'rows' ),
2268 'readonly' => 'readonly',
2269 'lang' => $pageLang->getHtmlCode(),
2270 'dir' => $pageLang->getDir(),
2272 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2274 // Show templates used by this article
2275 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2276 $this->addHTML( "<div class='templatesUsed'>
2282 # If the title doesn't exist, it's fairly pointless to print a return
2283 # link to it. After all, you just tried editing it and couldn't, so
2284 # what's there to do there?
2285 if( $this->getTitle()->exists() ) {
2286 $this->returnToMain( null, $this->getTitle() );
2291 * Turn off regular page output and return an error reponse
2292 * for when rate limiting has triggered.
2294 public function rateLimited() {
2295 throw new ThrottledError
;
2299 * Show a warning about slave lag
2301 * If the lag is higher than $wgSlaveLagCritical seconds,
2302 * then the warning is a bit more obvious. If the lag is
2303 * lower than $wgSlaveLagWarning, then no warning is shown.
2305 * @param $lag Integer: slave lag
2307 public function showLagWarning( $lag ) {
2308 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2309 if( $lag >= $wgSlaveLagWarning ) {
2310 $message = $lag < $wgSlaveLagCritical
2313 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2314 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2318 public function showFatalError( $message ) {
2319 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2321 $this->addHTML( $message );
2324 public function showUnexpectedValueError( $name, $val ) {
2325 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2328 public function showFileCopyError( $old, $new ) {
2329 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2332 public function showFileRenameError( $old, $new ) {
2333 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2336 public function showFileDeleteError( $name ) {
2337 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2340 public function showFileNotFoundError( $name ) {
2341 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2345 * Add a "return to" link pointing to a specified title
2347 * @param $title Title to link
2348 * @param $query String query string
2349 * @param $text String text of the link (input is not escaped)
2351 public function addReturnTo( $title, $query = array(), $text = null ) {
2352 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2353 $link = $this->msg( 'returnto' )->rawParams(
2354 Linker
::link( $title, $text, array(), $query ) )->escaped();
2355 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2359 * Add a "return to" link pointing to a specified title,
2360 * or the title indicated in the request, or else the main page
2363 * @param $returnto Title or String to return to
2364 * @param $returntoquery String: query string for the return to link
2366 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2367 if ( $returnto == null ) {
2368 $returnto = $this->getRequest()->getText( 'returnto' );
2371 if ( $returntoquery == null ) {
2372 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2375 if ( $returnto === '' ) {
2376 $returnto = Title
::newMainPage();
2379 if ( is_object( $returnto ) ) {
2380 $titleObj = $returnto;
2382 $titleObj = Title
::newFromText( $returnto );
2384 if ( !is_object( $titleObj ) ) {
2385 $titleObj = Title
::newMainPage();
2388 $this->addReturnTo( $titleObj, $returntoquery );
2392 * @param $sk Skin The given Skin
2393 * @param $includeStyle Boolean: unused
2394 * @return String: The doctype, opening <html>, and head element.
2396 public function headElement( Skin
$sk, $includeStyle = true ) {
2399 $userdir = $this->getLanguage()->getDir();
2400 $sitedir = $wgContLang->getDir();
2402 if ( $sk->commonPrintStylesheet() ) {
2403 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2406 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2408 if ( $this->getHTMLTitle() == '' ) {
2409 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2412 $openHead = Html
::openElement( 'head' );
2414 # Don't bother with the newline if $head == ''
2415 $ret .= "$openHead\n";
2418 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2420 $ret .= implode( "\n", array(
2421 $this->getHeadLinks( null, true ),
2422 $this->buildCssLinks(),
2423 $this->getHeadScripts(),
2424 $this->getHeadItems()
2427 $closeHead = Html
::closeElement( 'head' );
2429 $ret .= "$closeHead\n";
2432 $bodyAttrs = array();
2434 # Classes for LTR/RTL directionality support
2435 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2437 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2438 # A <body> class is probably not the best way to do this . . .
2439 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2441 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2442 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2443 $bodyAttrs['class'] .= ' action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2445 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2446 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2448 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2454 * Add the default ResourceLoader modules to this object
2456 private function addDefaultModules() {
2457 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2458 $wgAjaxWatch, $wgEnableMWSuggest;
2460 // Add base resources
2461 $this->addModules( array(
2463 'mediawiki.page.startup',
2464 'mediawiki.page.ready',
2466 if ( $wgIncludeLegacyJavaScript ){
2467 $this->addModules( 'mediawiki.legacy.wikibits' );
2470 if ( $wgPreloadJavaScriptMwUtil ) {
2471 $this->addModules( 'mediawiki.util' );
2474 MWDebug
::addModules( $this );
2476 // Add various resources if required
2478 $this->addModules( 'mediawiki.legacy.ajax' );
2480 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2482 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2483 $this->addModules( 'mediawiki.action.watch.ajax' );
2486 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2487 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2491 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2492 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2495 # Crazy edit-on-double-click stuff
2496 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2497 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2502 * Get a ResourceLoader object associated with this OutputPage
2504 * @return ResourceLoader
2506 public function getResourceLoader() {
2507 if ( is_null( $this->mResourceLoader
) ) {
2508 $this->mResourceLoader
= new ResourceLoader();
2510 return $this->mResourceLoader
;
2515 * @param $modules Array/string with the module name(s)
2516 * @param $only String ResourceLoaderModule TYPE_ class constant
2517 * @param $useESI boolean
2518 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2519 * @param $loadCall boolean If true, output a mw.loader.load() call rather than a <script src="..."> tag
2520 * @return string html <script> and <style> tags
2522 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2523 global $wgResourceLoaderUseESI, $wgResourceLoaderInlinePrivateModules;
2525 if ( !count( $modules ) ) {
2529 if ( count( $modules ) > 1 ) {
2530 // Remove duplicate module requests
2531 $modules = array_unique( (array) $modules );
2532 // Sort module names so requests are more uniform
2535 if ( ResourceLoader
::inDebugMode() ) {
2536 // Recursively call us for every item
2538 foreach ( $modules as $name ) {
2539 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2545 // Create keyed-by-group list of module objects from modules list
2547 $resourceLoader = $this->getResourceLoader();
2548 foreach ( (array) $modules as $name ) {
2549 $module = $resourceLoader->getModule( $name );
2550 # Check that we're allowed to include this module on this page
2552 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2553 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2554 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2555 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2561 $group = $module->getGroup();
2562 if ( !isset( $groups[$group] ) ) {
2563 $groups[$group] = array();
2565 $groups[$group][$name] = $module;
2569 foreach ( $groups as $group => $modules ) {
2570 // Special handling for user-specific groups
2572 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2573 $user = $this->getUser()->getName();
2576 // Create a fake request based on the one we are about to make so modules return
2577 // correct timestamp and emptiness data
2578 $query = ResourceLoader
::makeLoaderQuery(
2579 array(), // modules; not determined yet
2580 $this->getLanguage()->getCode(),
2581 $this->getSkin()->getSkinName(),
2583 null, // version; not determined yet
2584 ResourceLoader
::inDebugMode(),
2585 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2586 $this->isPrintable(),
2587 $this->getRequest()->getBool( 'handheld' ),
2590 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2591 // Drop modules that know they're empty
2592 foreach ( $modules as $key => $module ) {
2593 if ( $module->isKnownEmpty( $context ) ) {
2594 unset( $modules[$key] );
2597 // If there are no modules left, skip this group
2598 if ( $modules === array() ) {
2602 // Support inlining of private modules if configured as such. Note that these
2603 // modules should be loaded from getHeadScripts() before the first loader call.
2604 // Otherwise other modules can't properly use them as dependencies (bug 30914)
2605 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2606 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2607 $links .= Html
::inlineStyle(
2608 $resourceLoader->makeModuleResponse( $context, $modules )
2611 $links .= Html
::inlineScript(
2612 ResourceLoader
::makeLoaderConditionalScript(
2613 $resourceLoader->makeModuleResponse( $context, $modules )
2620 // Special handling for the user group; because users might change their stuff
2621 // on-wiki like user pages, or user preferences; we need to find the highest
2622 // timestamp of these user-changable modules so we can ensure cache misses on change
2623 // This should NOT be done for the site group (bug 27564) because anons get that too
2624 // and we shouldn't be putting timestamps in Squid-cached HTML
2626 if ( $group === 'user' ) {
2627 // Get the maximum timestamp
2629 foreach ( $modules as $module ) {
2630 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2632 // Add a version parameter so cache will break when things change
2633 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2636 $url = ResourceLoader
::makeLoaderURL(
2637 array_keys( $modules ),
2638 $this->getLanguage()->getCode(),
2639 $this->getSkin()->getSkinName(),
2642 ResourceLoader
::inDebugMode(),
2643 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2644 $this->isPrintable(),
2645 $this->getRequest()->getBool( 'handheld' ),
2648 if ( $useESI && $wgResourceLoaderUseESI ) {
2649 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2650 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2651 $link = Html
::inlineStyle( $esi );
2653 $link = Html
::inlineScript( $esi );
2656 // Automatically select style/script elements
2657 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2658 $link = Html
::linkedStyle( $url );
2659 } else if ( $loadCall ) {
2660 $link = Html
::inlineScript(
2661 ResourceLoader
::makeLoaderConditionalScript(
2662 Xml
::encodeJsCall( 'mw.loader.load', array( $url ) )
2666 $link = Html
::linkedScript( $url );
2670 if( $group == 'noscript' ){
2671 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2673 $links .= $link . "\n";
2680 * JS stuff to put in the <head>. This is the startup module, config
2681 * vars and modules marked with position 'top'
2683 * @return String: HTML fragment
2685 function getHeadScripts() {
2686 global $wgResourceLoaderExperimentalAsyncLoading;
2688 // Startup - this will immediately load jquery and mediawiki modules
2689 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2691 // Load config before anything else
2692 $scripts .= Html
::inlineScript(
2693 ResourceLoader
::makeLoaderConditionalScript(
2694 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2698 // Load embeddable private modules before any loader links
2699 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2700 // in mw.loader.implement() calls and deferred until mw.user is available
2701 $embedScripts = array( 'user.options', 'user.tokens' );
2702 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2704 // Script and Messages "only" requests marked for top inclusion
2705 // Messages should go first
2706 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2707 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2709 // Modules requests - let the client calculate dependencies and batch requests as it likes
2710 // Only load modules that have marked themselves for loading at the top
2711 $modules = $this->getModules( true, 'top' );
2713 $scripts .= Html
::inlineScript(
2714 ResourceLoader
::makeLoaderConditionalScript(
2715 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2720 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2721 $scripts .= $this->getScriptsForBottomQueue( true );
2728 * JS stuff to put at the 'bottom', which can either be the bottom of the <body>
2729 * or the bottom of the <head> depending on $wgResourceLoaderExperimentalAsyncLoading:
2730 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2731 * user preferences, site JS and user JS
2733 * @param $inHead boolean If true, this HTML goes into the <head>, if false it goes into the <body>
2736 function getScriptsForBottomQueue( $inHead ) {
2737 global $wgUseSiteJs, $wgAllowUserJs;
2739 // Script and Messages "only" requests marked for bottom inclusion
2740 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2741 // Messages should go first
2742 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2743 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2744 /* $loadCall = */ $inHead
2746 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2747 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2748 /* $loadCall = */ $inHead
2751 // Modules requests - let the client calculate dependencies and batch requests as it likes
2752 // Only load modules that have marked themselves for loading at the bottom
2753 $modules = $this->getModules( true, 'bottom' );
2755 $scripts .= Html
::inlineScript(
2756 ResourceLoader
::makeLoaderConditionalScript(
2757 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2763 $scripts .= "\n" . $this->mScripts
;
2765 $userScripts = array();
2767 // Add site JS if enabled
2768 if ( $wgUseSiteJs ) {
2769 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2770 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2772 if( $this->getUser()->isLoggedIn() ){
2773 $userScripts[] = 'user.groups';
2777 // Add user JS if enabled
2778 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2779 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2780 # XXX: additional security check/prompt?
2781 // We're on a preview of a JS subpage
2782 // Exclude this page from the user module in case it's in there (bug 26283)
2783 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2784 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2786 // Load the previewed JS
2787 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2789 // Include the user module normally
2790 // We can't do $userScripts[] = 'user'; because the user module would end up
2791 // being wrapped in a closure, so load it raw like 'site'
2792 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2793 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2797 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
,
2798 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2805 * JS stuff to put at the bottom of the <body>
2808 function getBottomScripts() {
2809 global $wgResourceLoaderExperimentalAsyncLoading;
2810 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2811 return $this->getScriptsForBottomQueue( false );
2818 * Add one or more variables to be set in mw.config in JavaScript.
2820 * @param $key {String|Array} Key or array of key/value pars.
2821 * @param $value {Mixed} [optional] Value of the configuration variable.
2823 public function addJsConfigVars( $keys, $value = null ) {
2824 if ( is_array( $keys ) ) {
2825 foreach ( $keys as $key => $value ) {
2826 $this->mJsConfigVars
[$key] = $value;
2831 $this->mJsConfigVars
[$keys] = $value;
2836 * Get an array containing the variables to be set in mw.config in JavaScript.
2838 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2839 * This is only public until that function is removed. You have been warned.
2841 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2842 * - in other words, page-independent/site-wide variables (without state).
2843 * You will only be adding bloat to the html page and causing page caches to
2844 * have to be purged on configuration changes.
2847 public function getJSVars() {
2848 global $wgUseAjax, $wgEnableMWSuggest;
2852 $canonicalName = false; # bug 21115
2854 $title = $this->getTitle();
2855 $ns = $title->getNamespace();
2856 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2858 if ( $ns == NS_SPECIAL
) {
2859 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2860 } elseif ( $this->canUseWikiPage() ) {
2861 $wikiPage = $this->getWikiPage();
2862 $latestRevID = $wikiPage->getLatest();
2863 $pageID = $wikiPage->getId();
2866 $lang = $title->getPageLanguage();
2868 // Pre-process information
2869 $separatorTransTable = $lang->separatorTransformTable();
2870 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2871 $compactSeparatorTransTable = array(
2872 implode( "\t", array_keys( $separatorTransTable ) ),
2873 implode( "\t", $separatorTransTable ),
2875 $digitTransTable = $lang->digitTransformTable();
2876 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2877 $compactDigitTransTable = array(
2878 implode( "\t", array_keys( $digitTransTable ) ),
2879 implode( "\t", $digitTransTable ),
2883 'wgCanonicalNamespace' => $nsname,
2884 'wgCanonicalSpecialPageName' => $canonicalName,
2885 'wgNamespaceNumber' => $title->getNamespace(),
2886 'wgPageName' => $title->getPrefixedDBKey(),
2887 'wgTitle' => $title->getText(),
2888 'wgCurRevisionId' => $latestRevID,
2889 'wgArticleId' => $pageID,
2890 'wgIsArticle' => $this->isArticle(),
2891 'wgAction' => Action
::getActionName( $this->getContext() ),
2892 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2893 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2894 'wgCategories' => $this->getCategories(),
2895 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2896 'wgPageContentLanguage' => $lang->getCode(),
2897 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2898 'wgDigitTransformTable' => $compactDigitTransTable,
2900 if ( $lang->hasVariants() ) {
2901 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2903 foreach ( $title->getRestrictionTypes() as $type ) {
2904 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2906 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2907 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2909 if ( $title->isMainPage() ) {
2910 $vars['wgIsMainPage'] = true;
2912 if ( $this->mRedirectedFrom
) {
2913 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBKey();
2916 // Allow extensions to add their custom variables to the mw.config map.
2917 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2918 // page-dependant but site-wide (without state).
2919 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2920 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2922 // Merge in variables from addJsConfigVars last
2923 return array_merge( $vars, $this->mJsConfigVars
);
2927 * To make it harder for someone to slip a user a fake
2928 * user-JavaScript or user-CSS preview, a random token
2929 * is associated with the login session. If it's not
2930 * passed back with the preview request, we won't render
2935 public function userCanPreview() {
2936 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2937 ||
!$this->getRequest()->wasPosted()
2938 ||
!$this->getUser()->matchEditToken(
2939 $this->getRequest()->getVal( 'wpEditToken' ) )
2943 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2947 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2952 * @param $addContentType bool
2954 * @return string HTML tag links to be put in the header.
2956 public function getHeadLinks( $unused = null, $addContentType = false ) {
2957 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2958 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2959 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2960 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2961 $wgRightsPage, $wgRightsUrl;
2965 if ( $addContentType ) {
2967 # More succinct than <meta http-equiv=Content-Type>, has the
2969 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2971 $tags[] = Html
::element( 'meta', array(
2972 'http-equiv' => 'Content-Type',
2973 'content' => "$wgMimeType; charset=UTF-8"
2975 $tags[] = Html
::element( 'meta', array( // bug 15835
2976 'http-equiv' => 'Content-Style-Type',
2977 'content' => 'text/css'
2982 $tags[] = Html
::element( 'meta', array(
2983 'name' => 'generator',
2984 'content' => "MediaWiki $wgVersion",
2987 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2988 if( $p !== 'index,follow' ) {
2989 // http://www.robotstxt.org/wc/meta-user.html
2990 // Only show if it's different from the default robots policy
2991 $tags[] = Html
::element( 'meta', array(
2997 if ( count( $this->mKeywords
) > 0 ) {
2999 "/<.*?" . ">/" => '',
3002 $tags[] = Html
::element( 'meta', array(
3003 'name' => 'keywords',
3004 'content' => preg_replace(
3005 array_keys( $strip ),
3006 array_values( $strip ),
3007 implode( ',', $this->mKeywords
)
3012 foreach ( $this->mMetatags
as $tag ) {
3013 $a = 'name'; // default attribute
3014 foreach ( self
::$metaAttrPrefixes as $prefix => $attribute ) {
3015 // Check if the name starts with the prefix
3016 if ( strpos( $tag[0], "$prefix:" ) === 0 ) {
3017 // Set the attribute name we're using
3019 // Strip the prefix from the name
3020 $tag[0] = substr( $tag[0], strlen( $prefix ) +
1 );
3024 $tags[] = Html
::element( 'meta',
3027 'content' => $tag[1]
3032 foreach ( $this->mLinktags
as $tag ) {
3033 $tags[] = Html
::element( 'link', $tag );
3036 # Universal edit button
3037 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3038 $user = $this->getUser();
3039 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3040 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3041 // Original UniversalEditButton
3042 $msg = $this->msg( 'edit' )->text();
3043 $tags[] = Html
::element( 'link', array(
3044 'rel' => 'alternate',
3045 'type' => 'application/x-wiki',
3047 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3049 // Alternate edit link
3050 $tags[] = Html
::element( 'link', array(
3053 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3058 # Generally the order of the favicon and apple-touch-icon links
3059 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3060 # uses whichever one appears later in the HTML source. Make sure
3061 # apple-touch-icon is specified first to avoid this.
3062 if ( $wgAppleTouchIcon !== false ) {
3063 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3066 if ( $wgFavicon !== false ) {
3067 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3070 # OpenSearch description link
3071 $tags[] = Html
::element( 'link', array(
3073 'type' => 'application/opensearchdescription+xml',
3074 'href' => wfScript( 'opensearch_desc' ),
3075 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3078 if ( $wgEnableAPI ) {
3079 # Real Simple Discovery link, provides auto-discovery information
3080 # for the MediaWiki API (and potentially additional custom API
3081 # support such as WordPress or Twitter-compatible APIs for a
3082 # blogging extension, etc)
3083 $tags[] = Html
::element( 'link', array(
3085 'type' => 'application/rsd+xml',
3086 // Output a protocol-relative URL here if $wgServer is protocol-relative
3087 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3088 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3094 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3095 $lang = $this->getTitle()->getPageLanguage();
3096 if ( $lang->hasVariants() ) {
3098 $urlvar = $lang->getURLVariant();
3101 $variants = $lang->getVariants();
3102 foreach ( $variants as $_v ) {
3103 $tags[] = Html
::element( 'link', array(
3104 'rel' => 'alternate',
3106 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3110 $tags[] = Html
::element( 'link', array(
3111 'rel' => 'canonical',
3112 'href' => $this->getTitle()->getCanonicalUrl()
3120 if ( $wgRightsPage ) {
3121 $copy = Title
::newFromText( $wgRightsPage );
3124 $copyright = $copy->getLocalURL();
3128 if ( !$copyright && $wgRightsUrl ) {
3129 $copyright = $wgRightsUrl;
3133 $tags[] = Html
::element( 'link', array(
3134 'rel' => 'copyright',
3135 'href' => $copyright )
3141 foreach( $this->getSyndicationLinks() as $format => $link ) {
3142 # Use the page name for the title. In principle, this could
3143 # lead to issues with having the same name for different feeds
3144 # corresponding to the same page, but we can't avoid that at
3147 $tags[] = $this->feedLink(
3150 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3151 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3155 # Recent changes feed should appear on every page (except recentchanges,
3156 # that would be redundant). Put it after the per-page feed to avoid
3157 # changing existing behavior. It's still available, probably via a
3158 # menu in your browser. Some sites might have a different feed they'd
3159 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3160 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3161 # If so, use it instead.
3162 if ( $wgOverrideSiteFeed ) {
3163 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3164 // Note, this->feedLink escapes the url.
3165 $tags[] = $this->feedLink(
3168 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3171 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3172 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3173 foreach ( $wgAdvertisedFeedTypes as $format ) {
3174 $tags[] = $this->feedLink(
3176 $rctitle->getLocalURL( "feed={$format}" ),
3177 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3182 return implode( "\n", $tags );
3186 * Generate a <link rel/> for a feed.
3188 * @param $type String: feed type
3189 * @param $url String: URL to the feed
3190 * @param $text String: value of the "title" attribute
3191 * @return String: HTML fragment
3193 private function feedLink( $type, $url, $text ) {
3194 return Html
::element( 'link', array(
3195 'rel' => 'alternate',
3196 'type' => "application/$type+xml",
3203 * Add a local or specified stylesheet, with the given media options.
3204 * Meant primarily for internal use...
3206 * @param $style String: URL to the file
3207 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3208 * @param $condition String: for IE conditional comments, specifying an IE version
3209 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3211 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3213 // Even though we expect the media type to be lowercase, but here we
3214 // force it to lowercase to be safe.
3216 $options['media'] = $media;
3219 $options['condition'] = $condition;
3222 $options['dir'] = $dir;
3224 $this->styles
[$style] = $options;
3228 * Adds inline CSS styles
3229 * @param $style_css Mixed: inline CSS
3230 * @param $flip String: Set to 'flip' to flip the CSS if needed
3232 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3233 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3234 # If wanted, and the interface is right-to-left, flip the CSS
3235 $style_css = CSSJanus
::transform( $style_css, true, false );
3237 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3241 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3242 * These will be applied to various media & IE conditionals.
3246 public function buildCssLinks() {
3247 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3248 $wgLang, $wgContLang;
3250 $this->getSkin()->setupSkinUserCss( $this );
3252 // Add ResourceLoader styles
3253 // Split the styles into four groups
3254 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3255 $otherTags = ''; // Tags to append after the normal <link> tags
3256 $resourceLoader = $this->getResourceLoader();
3258 $moduleStyles = $this->getModuleStyles();
3260 // Per-site custom styles
3261 if ( $wgUseSiteCss ) {
3262 $moduleStyles[] = 'site';
3263 $moduleStyles[] = 'noscript';
3264 if( $this->getUser()->isLoggedIn() ){
3265 $moduleStyles[] = 'user.groups';
3269 // Per-user custom styles
3270 if ( $wgAllowUserCss ) {
3271 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3272 // We're on a preview of a CSS subpage
3273 // Exclude this page from the user module in case it's in there (bug 26283)
3274 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3275 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3278 // Load the previewed CSS
3279 // If needed, Janus it first. This is user-supplied CSS, so it's
3280 // assumed to be right for the content language directionality.
3281 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3282 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3283 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3285 $otherTags .= Html
::inlineStyle( $previewedCSS );
3287 // Load the user styles normally
3288 $moduleStyles[] = 'user';
3292 // Per-user preference styles
3293 if ( $wgAllowUserCssPrefs ) {
3294 $moduleStyles[] = 'user.cssprefs';
3297 foreach ( $moduleStyles as $name ) {
3298 $module = $resourceLoader->getModule( $name );
3302 $group = $module->getGroup();
3303 // Modules in groups named "other" or anything different than "user", "site" or "private"
3304 // will be placed in the "other" group
3305 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3308 // We want site, private and user styles to override dynamically added styles from modules, but we want
3309 // dynamically added styles to override statically added styles from other modules. So the order
3310 // has to be other, dynamic, site, private, user
3311 // Add statically added styles for other modules
3312 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3313 // Add normal styles added through addStyle()/addInlineStyle() here
3314 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3315 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3316 // We use a <meta> tag with a made-up name for this because that's valid HTML
3317 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3319 // Add site, private and user styles
3320 // 'private' at present only contains user.options, so put that before 'user'
3321 // Any future private modules will likely have a similar user-specific character
3322 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3323 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3324 ResourceLoaderModule
::TYPE_STYLES
3328 // Add stuff in $otherTags (previewed user CSS if applicable)
3336 public function buildCssLinksArray() {
3339 // Add any extension CSS
3340 foreach ( $this->mExtStyles
as $url ) {
3341 $this->addStyle( $url );
3343 $this->mExtStyles
= array();
3345 foreach( $this->styles
as $file => $options ) {
3346 $link = $this->styleLink( $file, $options );
3348 $links[$file] = $link;
3355 * Generate \<link\> tags for stylesheets
3357 * @param $style String: URL to the file
3358 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3360 * @return String: HTML fragment
3362 protected function styleLink( $style, $options ) {
3363 if( isset( $options['dir'] ) ) {
3364 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3369 if( isset( $options['media'] ) ) {
3370 $media = self
::transformCssMedia( $options['media'] );
3371 if( is_null( $media ) ) {
3378 if( substr( $style, 0, 1 ) == '/' ||
3379 substr( $style, 0, 5 ) == 'http:' ||
3380 substr( $style, 0, 6 ) == 'https:' ) {
3383 global $wgStylePath, $wgStyleVersion;
3384 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3387 $link = Html
::linkedStyle( $url, $media );
3389 if( isset( $options['condition'] ) ) {
3390 $condition = htmlspecialchars( $options['condition'] );
3391 $link = "<!--[if $condition]>$link<![endif]-->";
3397 * Transform "media" attribute based on request parameters
3399 * @param $media String: current value of the "media" attribute
3400 * @return String: modified value of the "media" attribute
3402 public static function transformCssMedia( $media ) {
3403 global $wgRequest, $wgHandheldForIPhone;
3405 // Switch in on-screen display for media testing
3407 'printable' => 'print',
3408 'handheld' => 'handheld',
3410 foreach( $switches as $switch => $targetMedia ) {
3411 if( $wgRequest->getBool( $switch ) ) {
3412 if( $media == $targetMedia ) {
3414 } elseif( $media == 'screen' ) {
3420 // Expand longer media queries as iPhone doesn't grok 'handheld'
3421 if( $wgHandheldForIPhone ) {
3422 $mediaAliases = array(
3423 'screen' => 'screen and (min-device-width: 481px)',
3424 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3427 if( isset( $mediaAliases[$media] ) ) {
3428 $media = $mediaAliases[$media];
3436 * Add a wikitext-formatted message to the output.
3437 * This is equivalent to:
3439 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3441 public function addWikiMsg( /*...*/ ) {
3442 $args = func_get_args();
3443 $name = array_shift( $args );
3444 $this->addWikiMsgArray( $name, $args );
3448 * Add a wikitext-formatted message to the output.
3449 * Like addWikiMsg() except the parameters are taken as an array
3450 * instead of a variable argument list.
3452 * @param $name string
3453 * @param $args array
3455 public function addWikiMsgArray( $name, $args ) {
3456 $this->addWikiText( $this->msg( $name, $args )->plain() );
3460 * This function takes a number of message/argument specifications, wraps them in
3461 * some overall structure, and then parses the result and adds it to the output.
3463 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3464 * on. The subsequent arguments may either be strings, in which case they are the
3465 * message names, or arrays, in which case the first element is the message name,
3466 * and subsequent elements are the parameters to that message.
3468 * The special named parameter 'options' in a message specification array is passed
3469 * through to the $options parameter of wfMsgExt().
3471 * Don't use this for messages that are not in users interface language.
3475 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3479 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3481 * The newline after opening div is needed in some wikitext. See bug 19226.
3483 * @param $wrap string
3485 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3486 $msgSpecs = func_get_args();
3487 array_shift( $msgSpecs );
3488 $msgSpecs = array_values( $msgSpecs );
3490 foreach ( $msgSpecs as $n => $spec ) {
3492 if ( is_array( $spec ) ) {
3494 $name = array_shift( $args );
3495 if ( isset( $args['options'] ) ) {
3496 $options = $args['options'];
3497 unset( $args['options'] );
3503 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3505 $this->addWikiText( $s );
3509 * Include jQuery core. Use this to avoid loading it multiple times
3510 * before we get a usable script loader.
3512 * @param $modules Array: list of jQuery modules which should be loaded
3513 * @return Array: the list of modules which were not loaded.
3515 * @deprecated since 1.17
3517 public function includeJQuery( $modules = array() ) {