3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 class OutputPage
extends ContextSource
{
39 /// Should be private. Used with addMeta() which adds <meta>
40 var $mMetatags = array();
42 /// <meta keywords="stuff"> most of the time the first 10 links to an article
43 var $mKeywords = array();
45 var $mLinktags = array();
47 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
48 var $mExtStyles = array();
50 /// Should be private - has getter and setter. Contains the HTML title
53 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
57 * Holds the debug lines that will be output as comments in page source if
58 * $wgDebugComments is enabled. See also $wgShowDebug.
59 * TODO: make a getter method for this
61 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
63 /// Should be private. Stores contents of <title> tag
66 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
67 var $mIsarticle = false;
70 * Should be private. Has get/set methods properly documented.
71 * Stores "article flag" toggle.
73 var $mIsArticleRelated = true;
76 * Should be private. We have to set isPrintable(). Some pages should
77 * never be printed (ex: redirections).
79 var $mPrintable = false;
82 * Should be private. We have set/get/append methods.
84 * Contains the page subtitle. Special pages usually have some links here.
85 * Don't confuse with site subtitle added by skins.
87 private $mSubtitle = array();
93 * mLastModified and mEtag are used for sending cache control.
94 * The whole caching system should probably be moved into its own class.
96 var $mLastModified = '';
99 * Should be private. No getter but used in sendCacheControl();
100 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
101 * as a unique identifier for the content. It is later used by the client
102 * to compare its cached version with the server version. Client sends
103 * headers If-Match and If-None-Match containing its locally cached ETAG value.
105 * To get more information, you will have to look at HTTP/1.1 protocol which
106 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
110 var $mCategoryLinks = array();
111 var $mCategories = array();
113 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
114 var $mLanguageLinks = array();
117 * Should be private. Used for JavaScript (pre resource loader)
118 * We should split js / css.
119 * mScripts content is inserted as is in <head> by Skin. This might contains
120 * either a link to a stylesheet or inline css.
125 * Inline CSS styles. Use addInlineStyle() sparsingly
127 var $mInlineStyles = '';
133 * Used by skin template.
134 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
136 var $mPageLinkTitle = '';
138 /// Array of elements in <head>. Parser might add its own headers!
139 var $mHeadItems = array();
141 // @todo FIXME: Next variables probably comes from the resource loader
142 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
143 var $mResourceLoader;
144 var $mJsConfigVars = array();
146 /** @todo FIXME: Is this still used ?*/
147 var $mInlineMsg = array();
149 var $mTemplateIds = array();
150 var $mImageTimeKeys = array();
152 var $mRedirectCode = '';
154 var $mFeedLinksAppendQuery = null;
156 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
157 # @see ResourceLoaderModule::$origin
158 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
159 protected $mAllowedModules = array(
160 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
164 * @EasterEgg I just love the name for this self documenting variable.
167 var $mDoNothing = false;
170 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
173 * lazy initialised, use parserOptions()
176 protected $mParserOptions = null;
179 * Handles the atom / rss links.
180 * We probably only support atom in 2011.
181 * Looks like a private variable.
182 * @see $wgAdvertisedFeedTypes
184 var $mFeedLinks = array();
186 // Gwicke work on squid caching? Roughly from 2003.
187 var $mEnableClientCache = true;
190 * Flag if output should only contain the body of the article.
193 var $mArticleBodyOnly = false;
195 var $mNewSectionLink = false;
196 var $mHideNewSectionLink = false;
199 * Comes from the parser. This was probably made to load CSS/JS only
200 * if we had <gallery>. Used directly in CategoryPage.php
201 * Looks like resource loader can replace this.
203 var $mNoGallery = false;
205 // should be private.
206 var $mPageTitleActionText = '';
207 var $mParseWarnings = array();
209 // Cache stuff. Looks like mEnableClientCache
210 var $mSquidMaxage = 0;
213 var $mPreventClickjacking = true;
215 /// should be private. To include the variable {{REVISIONID}}
216 var $mRevisionId = null;
217 private $mRevisionTimestamp = null;
219 var $mFileVersion = null;
222 * An array of stylesheet filenames (relative from skins path), with options
223 * for CSS media, IE conditions, and RTL/LTR direction.
224 * For internal use; add settings in the skin via $this->addStyle()
226 * Style again! This seems like a code duplication since we already have
227 * mStyles. This is what makes OpenSource amazing.
229 var $styles = array();
232 * Whether jQuery is already handled.
234 protected $mJQueryDone = false;
236 private $mIndexPolicy = 'index';
237 private $mFollowPolicy = 'follow';
238 private $mVaryHeader = array(
239 'Accept-Encoding' => array( 'list-contains=gzip' ),
244 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
249 private $mRedirectedFrom = null;
252 * Constructor for OutputPage. This should not be called directly.
253 * Instead a new RequestContext should be created and it will implicitly create
254 * a OutputPage tied to that context.
256 function __construct( IContextSource
$context = null ) {
257 if ( $context === null ) {
258 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
259 wfDeprecated( __METHOD__
);
261 $this->setContext( $context );
266 * Redirect to $url rather than displaying the normal page
268 * @param $url String: URL
269 * @param $responsecode String: HTTP status code
271 public function redirect( $url, $responsecode = '302' ) {
272 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
273 $this->mRedirect
= str_replace( "\n", '', $url );
274 $this->mRedirectCode
= $responsecode;
278 * Get the URL to redirect to, or an empty string if not redirect URL set
282 public function getRedirect() {
283 return $this->mRedirect
;
287 * Set the HTTP status code to send with the output.
289 * @param $statusCode Integer
291 public function setStatusCode( $statusCode ) {
292 $this->mStatusCode
= $statusCode;
296 * Add a new <meta> tag
297 * To add an http-equiv meta tag, precede the name with "http:"
299 * @param $name String tag name
300 * @param $val String tag value
302 function addMeta( $name, $val ) {
303 array_push( $this->mMetatags
, array( $name, $val ) );
307 * Add a keyword or a list of keywords in the page header
309 * @param $text String or array of strings
311 function addKeyword( $text ) {
312 if( is_array( $text ) ) {
313 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
315 array_push( $this->mKeywords
, $text );
320 * Add a new \<link\> tag to the page header
322 * @param $linkarr Array: associative array of attributes.
324 function addLink( $linkarr ) {
325 array_push( $this->mLinktags
, $linkarr );
329 * Add a new \<link\> with "rel" attribute set to "meta"
331 * @param $linkarr Array: associative array mapping attribute names to their
332 * values, both keys and values will be escaped, and the
333 * "rel" attribute will be automatically added
335 function addMetadataLink( $linkarr ) {
336 $linkarr['rel'] = $this->getMetadataAttribute();
337 $this->addLink( $linkarr );
341 * Get the value of the "rel" attribute for metadata links
345 public function getMetadataAttribute() {
346 # note: buggy CC software only reads first "meta" link
347 static $haveMeta = false;
349 return 'alternate meta';
357 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
359 * @param $script String: raw HTML
361 function addScript( $script ) {
362 $this->mScripts
.= $script . "\n";
366 * Register and add a stylesheet from an extension directory.
368 * @param $url String path to sheet. Provide either a full url (beginning
369 * with 'http', etc) or a relative path from the document root
370 * (beginning with '/'). Otherwise it behaves identically to
371 * addStyle() and draws from the /skins folder.
373 public function addExtensionStyle( $url ) {
374 array_push( $this->mExtStyles
, $url );
378 * Get all styles added by extensions
382 function getExtStyle() {
383 return $this->mExtStyles
;
387 * Add a JavaScript file out of skins/common, or a given relative path.
389 * @param $file String: filename in skins/common or complete on-server path
391 * @param $version String: style version of the file. Defaults to $wgStyleVersion
393 public function addScriptFile( $file, $version = null ) {
394 global $wgStylePath, $wgStyleVersion;
395 // See if $file parameter is an absolute URL or begins with a slash
396 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
399 $path = "{$wgStylePath}/common/{$file}";
401 if ( is_null( $version ) )
402 $version = $wgStyleVersion;
403 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
407 * Add a self-contained script tag with the given contents
409 * @param $script String: JavaScript text, no <script> tags
411 public function addInlineScript( $script ) {
412 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
416 * Get all registered JS and CSS tags for the header.
420 function getScript() {
421 return $this->mScripts
. $this->getHeadItems();
425 * Filter an array of modules to remove insufficiently trustworthy members, and modules
426 * which are no longer registered (eg a page is cached before an extension is disabled)
427 * @param $modules Array
428 * @param $position String if not null, only return modules with this position
429 * @param $type string
432 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
433 $resourceLoader = $this->getResourceLoader();
434 $filteredModules = array();
435 foreach( $modules as $val ){
436 $module = $resourceLoader->getModule( $val );
437 if( $module instanceof ResourceLoaderModule
438 && $module->getOrigin() <= $this->getAllowedModules( $type )
439 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
441 $filteredModules[] = $val;
444 return $filteredModules;
448 * Get the list of modules to include on this page
450 * @param $filter Bool whether to filter out insufficiently trustworthy modules
451 * @param $position String if not null, only return modules with this position
452 * @param $param string
453 * @return Array of module names
455 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
456 $modules = array_values( array_unique( $this->$param ) );
458 ?
$this->filterModules( $modules, $position )
463 * Add one or more modules recognized by the resource loader. Modules added
464 * through this function will be loaded by the resource loader when the
467 * @param $modules Mixed: module name (string) or array of module names
469 public function addModules( $modules ) {
470 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
474 * Get the list of module JS to include on this page
479 * @return array of module names
481 public function getModuleScripts( $filter = false, $position = null ) {
482 return $this->getModules( $filter, $position, 'mModuleScripts' );
486 * Add only JS of one or more modules recognized by the resource loader. Module
487 * scripts added through this function will be loaded by the resource loader when
490 * @param $modules Mixed: module name (string) or array of module names
492 public function addModuleScripts( $modules ) {
493 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
497 * Get the list of module CSS to include on this page
502 * @return Array of module names
504 public function getModuleStyles( $filter = false, $position = null ) {
505 return $this->getModules( $filter, $position, 'mModuleStyles' );
509 * Add only CSS of one or more modules recognized by the resource loader. Module
510 * styles added through this function will be loaded by the resource loader when
513 * @param $modules Mixed: module name (string) or array of module names
515 public function addModuleStyles( $modules ) {
516 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
520 * Get the list of module messages to include on this page
525 * @return Array of module names
527 public function getModuleMessages( $filter = false, $position = null ) {
528 return $this->getModules( $filter, $position, 'mModuleMessages' );
532 * Add only messages of one or more modules recognized by the resource loader.
533 * Module messages added through this function will be loaded by the resource
534 * loader when the page loads.
536 * @param $modules Mixed: module name (string) or array of module names
538 public function addModuleMessages( $modules ) {
539 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
543 * Get an array of head items
547 function getHeadItemsArray() {
548 return $this->mHeadItems
;
552 * Get all header items in a string
556 function getHeadItems() {
558 foreach ( $this->mHeadItems
as $item ) {
565 * Add or replace an header item to the output
567 * @param $name String: item name
568 * @param $value String: raw HTML
570 public function addHeadItem( $name, $value ) {
571 $this->mHeadItems
[$name] = $value;
575 * Check if the header item $name is already set
577 * @param $name String: item name
580 public function hasHeadItem( $name ) {
581 return isset( $this->mHeadItems
[$name] );
585 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
587 * @param $tag String: value of "ETag" header
589 function setETag( $tag ) {
594 * Set whether the output should only contain the body of the article,
595 * without any skin, sidebar, etc.
596 * Used e.g. when calling with "action=render".
598 * @param $only Boolean: whether to output only the body of the article
600 public function setArticleBodyOnly( $only ) {
601 $this->mArticleBodyOnly
= $only;
605 * Return whether the output will contain only the body of the article
609 public function getArticleBodyOnly() {
610 return $this->mArticleBodyOnly
;
614 * checkLastModified tells the client to use the client-cached page if
615 * possible. If sucessful, the OutputPage is disabled so that
616 * any future call to OutputPage->output() have no effect.
618 * Side effect: sets mLastModified for Last-Modified header
620 * @param $timestamp string
622 * @return Boolean: true iff cache-ok headers was sent.
624 public function checkLastModified( $timestamp ) {
625 global $wgCachePages, $wgCacheEpoch;
627 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
628 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
631 if( !$wgCachePages ) {
632 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
635 if( $this->getUser()->getOption( 'nocache' ) ) {
636 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
640 $timestamp = wfTimestamp( TS_MW
, $timestamp );
641 $modifiedTimes = array(
642 'page' => $timestamp,
643 'user' => $this->getUser()->getTouched(),
644 'epoch' => $wgCacheEpoch
646 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
648 $maxModified = max( $modifiedTimes );
649 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
651 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
652 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
658 foreach ( $modifiedTimes as $name => $value ) {
659 if ( $info !== '' ) {
662 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
665 # IE sends sizes after the date like this:
666 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
667 # this breaks strtotime().
668 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
670 wfSuppressWarnings(); // E_STRICT system time bitching
671 $clientHeaderTime = strtotime( $clientHeader );
673 if ( !$clientHeaderTime ) {
674 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
677 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
679 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
680 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
681 wfDebug( __METHOD__
. ": effective Last-Modified: " .
682 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
683 if( $clientHeaderTime < $maxModified ) {
684 wfDebug( __METHOD__
. ": STALE, $info\n", false );
689 # Give a 304 response code and disable body output
690 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
691 ini_set( 'zlib.output_compression', 0 );
692 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
693 $this->sendCacheControl();
696 // Don't output a compressed blob when using ob_gzhandler;
697 // it's technically against HTTP spec and seems to confuse
698 // Firefox when the response gets split over two packets.
699 wfClearOutputBuffers();
705 * Override the last modified timestamp
707 * @param $timestamp String: new timestamp, in a format readable by
710 public function setLastModified( $timestamp ) {
711 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
715 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
717 * @param $policy String: the literal string to output as the contents of
718 * the meta tag. Will be parsed according to the spec and output in
722 public function setRobotPolicy( $policy ) {
723 $policy = Article
::formatRobotPolicy( $policy );
725 if( isset( $policy['index'] ) ) {
726 $this->setIndexPolicy( $policy['index'] );
728 if( isset( $policy['follow'] ) ) {
729 $this->setFollowPolicy( $policy['follow'] );
734 * Set the index policy for the page, but leave the follow policy un-
737 * @param $policy string Either 'index' or 'noindex'.
740 public function setIndexPolicy( $policy ) {
741 $policy = trim( $policy );
742 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
743 $this->mIndexPolicy
= $policy;
748 * Set the follow policy for the page, but leave the index policy un-
751 * @param $policy String: either 'follow' or 'nofollow'.
754 public function setFollowPolicy( $policy ) {
755 $policy = trim( $policy );
756 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
757 $this->mFollowPolicy
= $policy;
762 * Set the new value of the "action text", this will be added to the
763 * "HTML title", separated from it with " - ".
765 * @param $text String: new value of the "action text"
767 public function setPageTitleActionText( $text ) {
768 $this->mPageTitleActionText
= $text;
772 * Get the value of the "action text"
776 public function getPageTitleActionText() {
777 if ( isset( $this->mPageTitleActionText
) ) {
778 return $this->mPageTitleActionText
;
783 * "HTML title" means the contents of <title>.
784 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
786 * @param $name string
788 public function setHTMLTitle( $name ) {
789 if ( $name instanceof Message
) {
790 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
792 $this->mHTMLtitle
= $name;
797 * Return the "HTML title", i.e. the content of the <title> tag.
801 public function getHTMLTitle() {
802 return $this->mHTMLtitle
;
806 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
810 public function setRedirectedFrom( $t ) {
811 $this->mRedirectedFrom
= $t;
815 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
816 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
817 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
818 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
820 * @param $name string|Message
822 public function setPageTitle( $name ) {
823 if ( $name instanceof Message
) {
824 $name = $name->setContext( $this->getContext() )->text();
827 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
828 # but leave "<i>foobar</i>" alone
829 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
830 $this->mPagetitle
= $nameWithTags;
832 # change "<i>foo&bar</i>" to "foo&bar"
833 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
837 * Return the "page title", i.e. the content of the \<h1\> tag.
841 public function getPageTitle() {
842 return $this->mPagetitle
;
846 * Set the Title object to use
848 * @param $t Title object
850 public function setTitle( Title
$t ) {
851 $this->getContext()->setTitle( $t );
856 * Replace the subtile with $str
858 * @param $str String|Message: new value of the subtitle
860 public function setSubtitle( $str ) {
861 $this->clearSubtitle();
862 $this->addSubtitle( $str );
866 * Add $str to the subtitle
868 * @deprecated in 1.19; use addSubtitle() instead
869 * @param $str String|Message to add to the subtitle
871 public function appendSubtitle( $str ) {
872 $this->addSubtitle( $str );
876 * Add $str to the subtitle
878 * @param $str String|Message to add to the subtitle
880 public function addSubtitle( $str ) {
881 if ( $str instanceof Message
) {
882 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
884 $this->mSubtitle
[] = $str;
889 * Add a subtitle containing a backlink to a page
891 * @param $title Title to link to
893 public function addBacklinkSubtitle( Title
$title ) {
895 if ( $title->isRedirect() ) {
896 $query['redirect'] = 'no';
898 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
902 * Clear the subtitles
904 public function clearSubtitle() {
905 $this->mSubtitle
= array();
913 public function getSubtitle() {
914 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
918 * Set the page as printable, i.e. it'll be displayed with with all
919 * print styles included
921 public function setPrintable() {
922 $this->mPrintable
= true;
926 * Return whether the page is "printable"
930 public function isPrintable() {
931 return $this->mPrintable
;
935 * Disable output completely, i.e. calling output() will have no effect
937 public function disable() {
938 $this->mDoNothing
= true;
942 * Return whether the output will be completely disabled
946 public function isDisabled() {
947 return $this->mDoNothing
;
951 * Show an "add new section" link?
955 public function showNewSectionLink() {
956 return $this->mNewSectionLink
;
960 * Forcibly hide the new section link?
964 public function forceHideNewSectionLink() {
965 return $this->mHideNewSectionLink
;
969 * Add or remove feed links in the page header
970 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
971 * for the new version
974 * @param $show Boolean: true: add default feeds, false: remove all feeds
976 public function setSyndicated( $show = true ) {
978 $this->setFeedAppendQuery( false );
980 $this->mFeedLinks
= array();
985 * Add default feeds to the page header
986 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
987 * for the new version
990 * @param $val String: query to append to feed links or false to output
993 public function setFeedAppendQuery( $val ) {
994 global $wgAdvertisedFeedTypes;
996 $this->mFeedLinks
= array();
998 foreach ( $wgAdvertisedFeedTypes as $type ) {
999 $query = "feed=$type";
1000 if ( is_string( $val ) ) {
1001 $query .= '&' . $val;
1003 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1008 * Add a feed link to the page header
1010 * @param $format String: feed type, should be a key of $wgFeedClasses
1011 * @param $href String: URL
1013 public function addFeedLink( $format, $href ) {
1014 global $wgAdvertisedFeedTypes;
1016 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1017 $this->mFeedLinks
[$format] = $href;
1022 * Should we output feed links for this page?
1025 public function isSyndicated() {
1026 return count( $this->mFeedLinks
) > 0;
1030 * Return URLs for each supported syndication format for this page.
1031 * @return array associating format keys with URLs
1033 public function getSyndicationLinks() {
1034 return $this->mFeedLinks
;
1038 * Will currently always return null
1042 public function getFeedAppendQuery() {
1043 return $this->mFeedLinksAppendQuery
;
1047 * Set whether the displayed content is related to the source of the
1048 * corresponding article on the wiki
1049 * Setting true will cause the change "article related" toggle to true
1053 public function setArticleFlag( $v ) {
1054 $this->mIsarticle
= $v;
1056 $this->mIsArticleRelated
= $v;
1061 * Return whether the content displayed page is related to the source of
1062 * the corresponding article on the wiki
1066 public function isArticle() {
1067 return $this->mIsarticle
;
1071 * Set whether this page is related an article on the wiki
1072 * Setting false will cause the change of "article flag" toggle to false
1076 public function setArticleRelated( $v ) {
1077 $this->mIsArticleRelated
= $v;
1079 $this->mIsarticle
= false;
1084 * Return whether this page is related an article on the wiki
1088 public function isArticleRelated() {
1089 return $this->mIsArticleRelated
;
1093 * Add new language links
1095 * @param $newLinkArray array Associative array mapping language code to the page
1098 public function addLanguageLinks( $newLinkArray ) {
1099 $this->mLanguageLinks +
= $newLinkArray;
1103 * Reset the language links and add new language links
1105 * @param $newLinkArray array Associative array mapping language code to the page
1108 public function setLanguageLinks( $newLinkArray ) {
1109 $this->mLanguageLinks
= $newLinkArray;
1113 * Get the list of language links
1115 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1117 public function getLanguageLinks() {
1118 return $this->mLanguageLinks
;
1122 * Add an array of categories, with names in the keys
1124 * @param $categories Array mapping category name => sort key
1126 public function addCategoryLinks( $categories ) {
1129 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1133 # Add the links to a LinkBatch
1134 $arr = array( NS_CATEGORY
=> $categories );
1135 $lb = new LinkBatch
;
1136 $lb->setArray( $arr );
1138 # Fetch existence plus the hiddencat property
1139 $dbr = wfGetDB( DB_SLAVE
);
1140 $res = $dbr->select( array( 'page', 'page_props' ),
1141 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1142 $lb->constructSet( 'page', $dbr ),
1145 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1148 # Add the results to the link cache
1149 $lb->addResultToCache( LinkCache
::singleton(), $res );
1151 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1152 $categories = array_combine(
1153 array_keys( $categories ),
1154 array_fill( 0, count( $categories ), 'normal' )
1157 # Mark hidden categories
1158 foreach ( $res as $row ) {
1159 if ( isset( $row->pp_value
) ) {
1160 $categories[$row->page_title
] = 'hidden';
1164 # Add the remaining categories to the skin
1165 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1166 foreach ( $categories as $category => $type ) {
1167 $origcategory = $category;
1168 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1169 $wgContLang->findVariantLink( $category, $title, true );
1170 if ( $category != $origcategory ) {
1171 if ( array_key_exists( $category, $categories ) ) {
1175 $text = $wgContLang->convertHtml( $title->getText() );
1176 $this->mCategories
[] = $title->getText();
1177 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1183 * Reset the category links (but not the category list) and add $categories
1185 * @param $categories Array mapping category name => sort key
1187 public function setCategoryLinks( $categories ) {
1188 $this->mCategoryLinks
= array();
1189 $this->addCategoryLinks( $categories );
1193 * Get the list of category links, in a 2-D array with the following format:
1194 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1195 * hidden categories) and $link a HTML fragment with a link to the category
1200 public function getCategoryLinks() {
1201 return $this->mCategoryLinks
;
1205 * Get the list of category names this page belongs to
1207 * @return Array of strings
1209 public function getCategories() {
1210 return $this->mCategories
;
1214 * Do not allow scripts which can be modified by wiki users to load on this page;
1215 * only allow scripts bundled with, or generated by, the software.
1217 public function disallowUserJs() {
1218 $this->reduceAllowedModules(
1219 ResourceLoaderModule
::TYPE_SCRIPTS
,
1220 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1225 * Return whether user JavaScript is allowed for this page
1226 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1227 * trustworthiness is identified and enforced automagically.
1228 * Will be removed in 1.20.
1231 public function isUserJsAllowed() {
1232 wfDeprecated( __METHOD__
, '1.18' );
1233 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1237 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1238 * @see ResourceLoaderModule::$origin
1239 * @param $type String ResourceLoaderModule TYPE_ constant
1240 * @return Int ResourceLoaderModule ORIGIN_ class constant
1242 public function getAllowedModules( $type ){
1243 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1244 return min( array_values( $this->mAllowedModules
) );
1246 return isset( $this->mAllowedModules
[$type] )
1247 ?
$this->mAllowedModules
[$type]
1248 : ResourceLoaderModule
::ORIGIN_ALL
;
1253 * Set the highest level of CSS/JS untrustworthiness allowed
1254 * @param $type String ResourceLoaderModule TYPE_ constant
1255 * @param $level Int ResourceLoaderModule class constant
1257 public function setAllowedModules( $type, $level ){
1258 $this->mAllowedModules
[$type] = $level;
1262 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1263 * @param $type String
1264 * @param $level Int ResourceLoaderModule class constant
1266 public function reduceAllowedModules( $type, $level ){
1267 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1271 * Prepend $text to the body HTML
1273 * @param $text String: HTML
1275 public function prependHTML( $text ) {
1276 $this->mBodytext
= $text . $this->mBodytext
;
1280 * Append $text to the body HTML
1282 * @param $text String: HTML
1284 public function addHTML( $text ) {
1285 $this->mBodytext
.= $text;
1289 * Shortcut for adding an Html::element via addHTML.
1293 * @param $element string
1294 * @param $attribs array
1295 * @param $contents string
1297 public function addElement( $element, $attribs = array(), $contents = '' ) {
1298 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1302 * Clear the body HTML
1304 public function clearHTML() {
1305 $this->mBodytext
= '';
1311 * @return String: HTML
1313 public function getHTML() {
1314 return $this->mBodytext
;
1318 * Add $text to the debug output
1320 * @param $text String: debug text
1322 public function debug( $text ) {
1323 $this->mDebugtext
.= $text;
1327 * Get/set the ParserOptions object to use for wikitext parsing
1329 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1330 * current ParserOption object
1331 * @return ParserOptions object
1333 public function parserOptions( $options = null ) {
1334 if ( !$this->mParserOptions
) {
1335 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1336 $this->mParserOptions
->setEditSection( false );
1338 return wfSetVar( $this->mParserOptions
, $options );
1342 * Set the revision ID which will be seen by the wiki text parser
1343 * for things such as embedded {{REVISIONID}} variable use.
1345 * @param $revid Mixed: an positive integer, or null
1346 * @return Mixed: previous value
1348 public function setRevisionId( $revid ) {
1349 $val = is_null( $revid ) ?
null : intval( $revid );
1350 return wfSetVar( $this->mRevisionId
, $val );
1354 * Get the displayed revision ID
1358 public function getRevisionId() {
1359 return $this->mRevisionId
;
1363 * Set the timestamp of the revision which will be displayed. This is used
1364 * to avoid a extra DB call in Skin::lastModified().
1366 * @param $revid Mixed: string, or null
1367 * @return Mixed: previous value
1369 public function setRevisionTimestamp( $timestmap ) {
1370 return wfSetVar( $this->mRevisionTimestamp
, $timestmap );
1374 * Get the timestamp of displayed revision.
1375 * This will be null if not filled by setRevisionTimestamp().
1377 * @return String or null
1379 public function getRevisionTimestamp() {
1380 return $this->mRevisionTimestamp
;
1384 * Set the displayed file version
1386 * @param $file File|bool
1387 * @return Mixed: previous value
1389 public function setFileVersion( $file ) {
1391 if ( $file instanceof File
&& $file->exists() ) {
1392 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1394 return wfSetVar( $this->mFileVersion
, $val, true );
1398 * Get the displayed file version
1400 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1402 public function getFileVersion() {
1403 return $this->mFileVersion
;
1407 * Get the templates used on this page
1409 * @return Array (namespace => dbKey => revId)
1412 public function getTemplateIds() {
1413 return $this->mTemplateIds
;
1417 * Get the files used on this page
1419 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1422 public function getFileSearchOptions() {
1423 return $this->mImageTimeKeys
;
1427 * Convert wikitext to HTML and add it to the buffer
1428 * Default assumes that the current page title will be used.
1430 * @param $text String
1431 * @param $linestart Boolean: is this the start of a line?
1432 * @param $interface Boolean: is this text in the user interface language?
1434 public function addWikiText( $text, $linestart = true, $interface = true ) {
1435 $title = $this->getTitle(); // Work arround E_STRICT
1436 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1440 * Add wikitext with a custom Title object
1442 * @param $text String: wikitext
1443 * @param $title Title object
1444 * @param $linestart Boolean: is this the start of a line?
1446 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1447 $this->addWikiTextTitle( $text, $title, $linestart );
1451 * Add wikitext with a custom Title object and tidy enabled.
1453 * @param $text String: wikitext
1454 * @param $title Title object
1455 * @param $linestart Boolean: is this the start of a line?
1457 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1458 $this->addWikiTextTitle( $text, $title, $linestart, true );
1462 * Add wikitext with tidy enabled
1464 * @param $text String: wikitext
1465 * @param $linestart Boolean: is this the start of a line?
1467 public function addWikiTextTidy( $text, $linestart = true ) {
1468 $title = $this->getTitle();
1469 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1473 * Add wikitext with a custom Title object
1475 * @param $text String: wikitext
1476 * @param $title Title object
1477 * @param $linestart Boolean: is this the start of a line?
1478 * @param $tidy Boolean: whether to use tidy
1479 * @param $interface Boolean: whether it is an interface message
1480 * (for example disables conversion)
1482 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1485 wfProfileIn( __METHOD__
);
1487 $popts = $this->parserOptions();
1488 $oldTidy = $popts->setTidy( $tidy );
1489 $popts->setInterfaceMessage( (bool) $interface );
1491 $parserOutput = $wgParser->parse(
1492 $text, $title, $popts,
1493 $linestart, true, $this->mRevisionId
1496 $popts->setTidy( $oldTidy );
1498 $this->addParserOutput( $parserOutput );
1500 wfProfileOut( __METHOD__
);
1504 * Add a ParserOutput object, but without Html
1506 * @param $parserOutput ParserOutput object
1508 public function addParserOutputNoText( &$parserOutput ) {
1509 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1510 $this->addCategoryLinks( $parserOutput->getCategories() );
1511 $this->mNewSectionLink
= $parserOutput->getNewSection();
1512 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1514 $this->mParseWarnings
= $parserOutput->getWarnings();
1515 if ( !$parserOutput->isCacheable() ) {
1516 $this->enableClientCache( false );
1518 $this->mNoGallery
= $parserOutput->getNoGallery();
1519 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1520 $this->addModules( $parserOutput->getModules() );
1521 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1522 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1523 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1525 // Template versioning...
1526 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1527 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1528 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1530 $this->mTemplateIds
[$ns] = $dbks;
1533 // File versioning...
1534 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1535 $this->mImageTimeKeys
[$dbk] = $data;
1538 // Hooks registered in the object
1539 global $wgParserOutputHooks;
1540 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1541 list( $hookName, $data ) = $hookInfo;
1542 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1543 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1547 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1551 * Add a ParserOutput object
1553 * @param $parserOutput ParserOutput
1555 function addParserOutput( &$parserOutput ) {
1556 $this->addParserOutputNoText( $parserOutput );
1557 $text = $parserOutput->getText();
1558 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1559 $this->addHTML( $text );
1564 * Add the output of a QuickTemplate to the output buffer
1566 * @param $template QuickTemplate
1568 public function addTemplate( &$template ) {
1570 $template->execute();
1571 $this->addHTML( ob_get_contents() );
1576 * Parse wikitext and return the HTML.
1578 * @param $text String
1579 * @param $linestart Boolean: is this the start of a line?
1580 * @param $interface Boolean: use interface language ($wgLang instead of
1581 * $wgContLang) while parsing language sensitive magic
1582 * words like GRAMMAR and PLURAL. This also disables
1583 * LanguageConverter.
1584 * @param $language Language object: target language object, will override
1586 * @return String: HTML
1588 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1591 if( is_null( $this->getTitle() ) ) {
1592 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1595 $popts = $this->parserOptions();
1597 $popts->setInterfaceMessage( true );
1599 if ( $language !== null ) {
1600 $oldLang = $popts->setTargetLanguage( $language );
1603 $parserOutput = $wgParser->parse(
1604 $text, $this->getTitle(), $popts,
1605 $linestart, true, $this->mRevisionId
1609 $popts->setInterfaceMessage( false );
1611 if ( $language !== null ) {
1612 $popts->setTargetLanguage( $oldLang );
1615 return $parserOutput->getText();
1619 * Parse wikitext, strip paragraphs, and return the HTML.
1621 * @param $text String
1622 * @param $linestart Boolean: is this the start of a line?
1623 * @param $interface Boolean: use interface language ($wgLang instead of
1624 * $wgContLang) while parsing language sensitive magic
1625 * words like GRAMMAR and PLURAL
1626 * @return String: HTML
1628 public function parseInline( $text, $linestart = true, $interface = false ) {
1629 $parsed = $this->parse( $text, $linestart, $interface );
1632 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1640 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1642 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1644 public function setSquidMaxage( $maxage ) {
1645 $this->mSquidMaxage
= $maxage;
1649 * Use enableClientCache(false) to force it to send nocache headers
1651 * @param $state bool
1655 public function enableClientCache( $state ) {
1656 return wfSetVar( $this->mEnableClientCache
, $state );
1660 * Get the list of cookies that will influence on the cache
1664 function getCacheVaryCookies() {
1665 global $wgCookiePrefix, $wgCacheVaryCookies;
1667 if ( $cookies === null ) {
1668 $cookies = array_merge(
1670 "{$wgCookiePrefix}Token",
1671 "{$wgCookiePrefix}LoggedOut",
1676 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1682 * Check if the request has a cache-varying cookie header
1683 * If it does, it's very important that we don't allow public caching
1687 function haveCacheVaryCookies() {
1688 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1689 if ( $cookieHeader === false ) {
1692 $cvCookies = $this->getCacheVaryCookies();
1693 foreach ( $cvCookies as $cookieName ) {
1694 # Check for a simple string match, like the way squid does it
1695 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1696 wfDebug( __METHOD__
. ": found $cookieName\n" );
1700 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1705 * Add an HTTP header that will influence on the cache
1707 * @param $header String: header name
1708 * @param $option Array|null
1709 * @todo FIXME: Document the $option parameter; it appears to be for
1710 * X-Vary-Options but what format is acceptable?
1712 public function addVaryHeader( $header, $option = null ) {
1713 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1714 $this->mVaryHeader
[$header] = (array)$option;
1715 } elseif( is_array( $option ) ) {
1716 if( is_array( $this->mVaryHeader
[$header] ) ) {
1717 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1719 $this->mVaryHeader
[$header] = $option;
1722 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1726 * Get a complete X-Vary-Options header
1730 public function getXVO() {
1731 $cvCookies = $this->getCacheVaryCookies();
1733 $cookiesOption = array();
1734 foreach ( $cvCookies as $cookieName ) {
1735 $cookiesOption[] = 'string-contains=' . $cookieName;
1737 $this->addVaryHeader( 'Cookie', $cookiesOption );
1740 foreach( $this->mVaryHeader
as $header => $option ) {
1741 $newheader = $header;
1742 if ( is_array( $option ) && count( $option ) > 0 ) {
1743 $newheader .= ';' . implode( ';', $option );
1745 $headers[] = $newheader;
1747 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1753 * bug 21672: Add Accept-Language to Vary and XVO headers
1754 * if there's no 'variant' parameter existed in GET.
1757 * /w/index.php?title=Main_page should always be served; but
1758 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1760 function addAcceptLanguage() {
1761 $lang = $this->getTitle()->getPageLanguage();
1762 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1763 $variants = $lang->getVariants();
1764 $aloption = array();
1765 foreach ( $variants as $variant ) {
1766 if( $variant === $lang->getCode() ) {
1769 $aloption[] = 'string-contains=' . $variant;
1771 // IE and some other browsers use another form of language code
1772 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1773 // We should handle these too.
1774 $ievariant = explode( '-', $variant );
1775 if ( count( $ievariant ) == 2 ) {
1776 $ievariant[1] = strtoupper( $ievariant[1] );
1777 $ievariant = implode( '-', $ievariant );
1778 $aloption[] = 'string-contains=' . $ievariant;
1782 $this->addVaryHeader( 'Accept-Language', $aloption );
1787 * Set a flag which will cause an X-Frame-Options header appropriate for
1788 * edit pages to be sent. The header value is controlled by
1789 * $wgEditPageFrameOptions.
1791 * This is the default for special pages. If you display a CSRF-protected
1792 * form on an ordinary view page, then you need to call this function.
1794 * @param $enable bool
1796 public function preventClickjacking( $enable = true ) {
1797 $this->mPreventClickjacking
= $enable;
1801 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1802 * This can be called from pages which do not contain any CSRF-protected
1805 public function allowClickjacking() {
1806 $this->mPreventClickjacking
= false;
1810 * Get the X-Frame-Options header value (without the name part), or false
1811 * if there isn't one. This is used by Skin to determine whether to enable
1812 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1816 public function getFrameOptions() {
1817 global $wgBreakFrames, $wgEditPageFrameOptions;
1818 if ( $wgBreakFrames ) {
1820 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1821 return $wgEditPageFrameOptions;
1827 * Send cache control HTTP headers
1829 public function sendCacheControl() {
1830 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1832 $response = $this->getRequest()->response();
1833 if ( $wgUseETag && $this->mETag
) {
1834 $response->header( "ETag: $this->mETag" );
1837 $this->addAcceptLanguage();
1839 # don't serve compressed data to clients who can't handle it
1840 # maintain different caches for logged-in users and non-logged in ones
1841 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1844 # Add an X-Vary-Options header for Squid with Wikimedia patches
1845 $response->header( $this->getXVO() );
1848 if( $this->mEnableClientCache
) {
1850 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1851 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1855 # We'll purge the proxy cache explicitly, but require end user agents
1856 # to revalidate against the proxy on each visit.
1857 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1858 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1859 # start with a shorter timeout for initial testing
1860 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1861 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1862 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1864 # We'll purge the proxy cache for anons explicitly, but require end user agents
1865 # to revalidate against the proxy on each visit.
1866 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1867 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1868 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1869 # start with a shorter timeout for initial testing
1870 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1871 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1874 # We do want clients to cache if they can, but they *must* check for updates
1875 # on revisiting the page.
1876 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1877 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1878 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1880 if($this->mLastModified
) {
1881 $response->header( "Last-Modified: {$this->mLastModified}" );
1884 wfDebug( __METHOD__
. ": no caching **\n", false );
1886 # In general, the absence of a last modified header should be enough to prevent
1887 # the client from using its cache. We send a few other things just to make sure.
1888 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1889 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1890 $response->header( 'Pragma: no-cache' );
1895 * Get the message associed with the HTTP response code $code
1897 * @param $code Integer: status code
1898 * @return String or null: message or null if $code is not in the list of
1901 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1903 public static function getStatusMessage( $code ) {
1904 wfDeprecated( __METHOD__
);
1905 return HttpStatus
::getMessage( $code );
1909 * Finally, all the text has been munged and accumulated into
1910 * the object, let's actually output it:
1912 public function output() {
1913 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1915 if( $this->mDoNothing
) {
1919 wfProfileIn( __METHOD__
);
1921 $response = $this->getRequest()->response();
1923 if ( $this->mRedirect
!= '' ) {
1924 # Standards require redirect URLs to be absolute
1925 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1927 $redirect = $this->mRedirect
;
1928 $code = $this->mRedirectCode
;
1930 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1931 if( $code == '301' ||
$code == '303' ) {
1932 if( !$wgDebugRedirects ) {
1933 $message = HttpStatus
::getMessage( $code );
1934 $response->header( "HTTP/1.1 $code $message" );
1936 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1938 if ( $wgVaryOnXFP ) {
1939 $this->addVaryHeader( 'X-Forwarded-Proto' );
1941 $this->sendCacheControl();
1943 $response->header( "Content-Type: text/html; charset=utf-8" );
1944 if( $wgDebugRedirects ) {
1945 $url = htmlspecialchars( $redirect );
1946 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1947 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1948 print "</body>\n</html>\n";
1950 $response->header( 'Location: ' . $redirect );
1954 wfProfileOut( __METHOD__
);
1956 } elseif ( $this->mStatusCode
) {
1957 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1959 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1963 # Buffer output; final headers may depend on later processing
1966 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1967 $response->header( 'Content-language: ' . $wgLanguageCode );
1969 // Prevent framing, if requested
1970 $frameOptions = $this->getFrameOptions();
1971 if ( $frameOptions ) {
1972 $response->header( "X-Frame-Options: $frameOptions" );
1975 if ( $this->mArticleBodyOnly
) {
1976 $this->out( $this->mBodytext
);
1978 $this->addDefaultModules();
1980 $sk = $this->getSkin();
1982 // Hook that allows last minute changes to the output page, e.g.
1983 // adding of CSS or Javascript by extensions.
1984 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1986 wfProfileIn( 'Output-skin' );
1988 wfProfileOut( 'Output-skin' );
1991 $this->sendCacheControl();
1993 wfProfileOut( __METHOD__
);
1997 * Actually output something with print().
1999 * @param $ins String: the string to output
2001 public function out( $ins ) {
2006 * Produce a "user is blocked" page.
2007 * @deprecated since 1.18
2009 function blockedPage() {
2010 throw new UserBlockedError( $this->getUser()->mBlock
);
2014 * Prepare this object to display an error page; disable caching and
2015 * indexing, clear the current text and redirect, set the page's title
2016 * and optionally an custom HTML title (content of the <title> tag).
2018 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2019 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2020 * optional, if not passed the <title> attribute will be
2021 * based on $pageTitle
2023 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2024 if ( $this->getTitle() ) {
2025 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
2028 $this->setPageTitle( $pageTitle );
2029 if ( $htmlTitle !== false ) {
2030 $this->setHTMLTitle( $htmlTitle );
2032 $this->setRobotPolicy( 'noindex,nofollow' );
2033 $this->setArticleRelated( false );
2034 $this->enableClientCache( false );
2035 $this->mRedirect
= '';
2036 $this->clearSubtitle();
2041 * Output a standard error page
2043 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2044 * showErrorPage( 'titlemsg', $messageObject );
2046 * @param $title String: message key for page title
2047 * @param $msg Mixed: message key (string) for page text, or a Message object
2048 * @param $params Array: message parameters; ignored if $msg is a Message object
2050 public function showErrorPage( $title, $msg, $params = array() ) {
2051 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2053 if ( $msg instanceof Message
){
2054 $this->addHTML( $msg->parse() );
2056 $this->addWikiMsgArray( $msg, $params );
2059 $this->returnToMain();
2063 * Output a standard permission error page
2065 * @param $errors Array: error message keys
2066 * @param $action String: action that was denied or null if unknown
2068 public function showPermissionsErrorPage( $errors, $action = null ) {
2069 global $wgGroupPermissions;
2071 // For some action (read, edit, create and upload), display a "login to do this action"
2072 // error if all of the following conditions are met:
2073 // 1. the user is not logged in
2074 // 2. the only error is insufficient permissions (i.e. no block or something else)
2075 // 3. the error can be avoided simply by logging in
2076 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2077 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2078 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2079 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2080 ||
( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2082 $displayReturnto = null;
2084 # Due to bug 32276, if a user does not have read permissions,
2085 # $this->getTitle() will just give Special:Badtitle, which is
2086 # not especially useful as a returnto parameter. Use the title
2087 # from the request instead, if there was one.
2088 $request = $this->getRequest();
2089 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2090 if ( $action == 'edit' ) {
2091 $msg = 'whitelistedittext';
2092 $displayReturnto = $returnto;
2093 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2094 $msg = 'nocreatetext';
2095 } elseif ( $action == 'upload' ) {
2096 $msg = 'uploadnologintext';
2098 $msg = 'loginreqpagetext';
2099 $displayReturnto = Title
::newMainPage();
2105 $query['returnto'] = $returnto->getPrefixedText();
2107 if ( !$request->wasPosted() ) {
2108 $returntoquery = $request->getValues();
2109 unset( $returntoquery['title'] );
2110 unset( $returntoquery['returnto'] );
2111 unset( $returntoquery['returntoquery'] );
2112 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2115 $loginLink = Linker
::linkKnown(
2116 SpecialPage
::getTitleFor( 'Userlogin' ),
2117 $this->msg( 'loginreqlink' )->escaped(),
2122 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2123 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2125 # Don't return to a page the user can't read otherwise
2126 # we'll end up in a pointless loop
2127 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2128 $this->returnToMain( null, $displayReturnto );
2131 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2132 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2137 * Display an error page indicating that a given version of MediaWiki is
2138 * required to use it
2140 * @param $version Mixed: the version of MediaWiki needed to use the page
2142 public function versionRequired( $version ) {
2143 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2145 $this->addWikiMsg( 'versionrequiredtext', $version );
2146 $this->returnToMain();
2150 * Display an error page noting that a given permission bit is required.
2151 * @deprecated since 1.18, just throw the exception directly
2152 * @param $permission String: key required
2154 public function permissionRequired( $permission ) {
2155 throw new PermissionsError( $permission );
2159 * Produce the stock "please login to use the wiki" page
2161 * @deprecated in 1.19; throw the exception directly
2163 public function loginToUse() {
2164 throw new PermissionsError( 'read' );
2168 * Format a list of error messages
2170 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2171 * @param $action String: action that was denied or null if unknown
2172 * @return String: the wikitext error-messages, formatted into a list.
2174 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2175 if ( $action == null ) {
2176 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2178 $action_desc = $this->msg( "action-$action" )->plain();
2180 'permissionserrorstext-withaction',
2183 )->plain() . "\n\n";
2186 if ( count( $errors ) > 1 ) {
2187 $text .= '<ul class="permissions-errors">' . "\n";
2189 foreach( $errors as $error ) {
2191 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2196 $text .= "<div class=\"permissions-errors\">\n" .
2197 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2205 * Display a page stating that the Wiki is in read-only mode,
2206 * and optionally show the source of the page that the user
2207 * was trying to edit. Should only be called (for this
2208 * purpose) after wfReadOnly() has returned true.
2210 * For historical reasons, this function is _also_ used to
2211 * show the error message when a user tries to edit a page
2212 * they are not allowed to edit. (Unless it's because they're
2213 * blocked, then we show blockedPage() instead.) In this
2214 * case, the second parameter should be set to true and a list
2215 * of reasons supplied as the third parameter.
2217 * @todo Needs to be split into multiple functions.
2219 * @param $source String: source code to show (or null).
2220 * @param $protected Boolean: is this a permissions error?
2221 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2222 * @param $action String: action that was denied or null if unknown
2224 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2225 $this->setRobotPolicy( 'noindex,nofollow' );
2226 $this->setArticleRelated( false );
2228 // If no reason is given, just supply a default "I can't let you do
2229 // that, Dave" message. Should only occur if called by legacy code.
2230 if ( $protected && empty( $reasons ) ) {
2231 $reasons[] = array( 'badaccess-group0' );
2234 if ( !empty( $reasons ) ) {
2235 // Permissions error
2237 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2238 $this->addBacklinkSubtitle( $this->getTitle() );
2240 $this->setPageTitle( $this->msg( 'badaccess' ) );
2242 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2244 // Wiki is read only
2245 throw new ReadOnlyError
;
2248 // Show source, if supplied
2249 if( is_string( $source ) ) {
2250 $this->addWikiMsg( 'viewsourcetext' );
2252 $pageLang = $this->getTitle()->getPageLanguage();
2254 'id' => 'wpTextbox1',
2255 'name' => 'wpTextbox1',
2256 'cols' => $this->getUser()->getOption( 'cols' ),
2257 'rows' => $this->getUser()->getOption( 'rows' ),
2258 'readonly' => 'readonly',
2259 'lang' => $pageLang->getHtmlCode(),
2260 'dir' => $pageLang->getDir(),
2262 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2264 // Show templates used by this article
2265 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2266 $this->addHTML( "<div class='templatesUsed'>
2272 # If the title doesn't exist, it's fairly pointless to print a return
2273 # link to it. After all, you just tried editing it and couldn't, so
2274 # what's there to do there?
2275 if( $this->getTitle()->exists() ) {
2276 $this->returnToMain( null, $this->getTitle() );
2281 * Turn off regular page output and return an error reponse
2282 * for when rate limiting has triggered.
2284 public function rateLimited() {
2285 throw new ThrottledError
;
2289 * Show a warning about slave lag
2291 * If the lag is higher than $wgSlaveLagCritical seconds,
2292 * then the warning is a bit more obvious. If the lag is
2293 * lower than $wgSlaveLagWarning, then no warning is shown.
2295 * @param $lag Integer: slave lag
2297 public function showLagWarning( $lag ) {
2298 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2299 if( $lag >= $wgSlaveLagWarning ) {
2300 $message = $lag < $wgSlaveLagCritical
2303 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2304 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2308 public function showFatalError( $message ) {
2309 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2311 $this->addHTML( $message );
2314 public function showUnexpectedValueError( $name, $val ) {
2315 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2318 public function showFileCopyError( $old, $new ) {
2319 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2322 public function showFileRenameError( $old, $new ) {
2323 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2326 public function showFileDeleteError( $name ) {
2327 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2330 public function showFileNotFoundError( $name ) {
2331 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2335 * Add a "return to" link pointing to a specified title
2337 * @param $title Title to link
2338 * @param $query String query string
2339 * @param $text String text of the link (input is not escaped)
2341 public function addReturnTo( $title, $query = array(), $text = null ) {
2342 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2343 $link = $this->msg( 'returnto' )->rawParams(
2344 Linker
::link( $title, $text, array(), $query ) )->escaped();
2345 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2349 * Add a "return to" link pointing to a specified title,
2350 * or the title indicated in the request, or else the main page
2353 * @param $returnto Title or String to return to
2354 * @param $returntoquery String: query string for the return to link
2356 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2357 if ( $returnto == null ) {
2358 $returnto = $this->getRequest()->getText( 'returnto' );
2361 if ( $returntoquery == null ) {
2362 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2365 if ( $returnto === '' ) {
2366 $returnto = Title
::newMainPage();
2369 if ( is_object( $returnto ) ) {
2370 $titleObj = $returnto;
2372 $titleObj = Title
::newFromText( $returnto );
2374 if ( !is_object( $titleObj ) ) {
2375 $titleObj = Title
::newMainPage();
2378 $this->addReturnTo( $titleObj, $returntoquery );
2382 * @param $sk Skin The given Skin
2383 * @param $includeStyle Boolean: unused
2384 * @return String: The doctype, opening <html>, and head element.
2386 public function headElement( Skin
$sk, $includeStyle = true ) {
2389 $userdir = $this->getLanguage()->getDir();
2390 $sitedir = $wgContLang->getDir();
2392 if ( $sk->commonPrintStylesheet() ) {
2393 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2396 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2398 if ( $this->getHTMLTitle() == '' ) {
2399 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2402 $openHead = Html
::openElement( 'head' );
2404 # Don't bother with the newline if $head == ''
2405 $ret .= "$openHead\n";
2408 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2410 $ret .= implode( "\n", array(
2411 $this->getHeadLinks( null, true ),
2412 $this->buildCssLinks(),
2413 $this->getHeadScripts(),
2414 $this->getHeadItems()
2417 $closeHead = Html
::closeElement( 'head' );
2419 $ret .= "$closeHead\n";
2422 $bodyAttrs = array();
2424 # Classes for LTR/RTL directionality support
2425 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2427 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2428 # A <body> class is probably not the best way to do this . . .
2429 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2431 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2432 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2433 $bodyAttrs['class'] .= ' action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2435 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2436 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2438 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2444 * Add the default ResourceLoader modules to this object
2446 private function addDefaultModules() {
2447 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2448 $wgAjaxWatch, $wgEnableMWSuggest;
2450 // Add base resources
2451 $this->addModules( array(
2453 'mediawiki.page.startup',
2454 'mediawiki.page.ready',
2456 if ( $wgIncludeLegacyJavaScript ){
2457 $this->addModules( 'mediawiki.legacy.wikibits' );
2460 if ( $wgPreloadJavaScriptMwUtil ) {
2461 $this->addModules( 'mediawiki.util' );
2464 MWDebug
::addModules( $this );
2466 // Add various resources if required
2468 $this->addModules( 'mediawiki.legacy.ajax' );
2470 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2472 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2473 $this->addModules( 'mediawiki.action.watch.ajax' );
2476 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2477 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2481 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2482 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2485 # Crazy edit-on-double-click stuff
2486 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2487 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2492 * Get a ResourceLoader object associated with this OutputPage
2494 * @return ResourceLoader
2496 public function getResourceLoader() {
2497 if ( is_null( $this->mResourceLoader
) ) {
2498 $this->mResourceLoader
= new ResourceLoader();
2500 return $this->mResourceLoader
;
2505 * @param $modules Array/string with the module name(s)
2506 * @param $only String ResourceLoaderModule TYPE_ class constant
2507 * @param $useESI boolean
2508 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2509 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a <script src="..."> tag
2510 * @return string html <script> and <style> tags
2512 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2513 global $wgResourceLoaderUseESI;
2515 if ( !count( $modules ) ) {
2519 if ( count( $modules ) > 1 ) {
2520 // Remove duplicate module requests
2521 $modules = array_unique( (array) $modules );
2522 // Sort module names so requests are more uniform
2525 if ( ResourceLoader
::inDebugMode() ) {
2526 // Recursively call us for every item
2528 foreach ( $modules as $name ) {
2529 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2535 // Create keyed-by-group list of module objects from modules list
2537 $resourceLoader = $this->getResourceLoader();
2538 foreach ( (array) $modules as $name ) {
2539 $module = $resourceLoader->getModule( $name );
2540 # Check that we're allowed to include this module on this page
2542 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2543 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2544 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2545 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2551 $group = $module->getGroup();
2552 if ( !isset( $groups[$group] ) ) {
2553 $groups[$group] = array();
2555 $groups[$group][$name] = $module;
2559 foreach ( $groups as $group => $modules ) {
2560 // Special handling for user-specific groups
2562 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2563 $user = $this->getUser()->getName();
2566 // Create a fake request based on the one we are about to make so modules return
2567 // correct timestamp and emptiness data
2568 $query = ResourceLoader
::makeLoaderQuery(
2569 array(), // modules; not determined yet
2570 $this->getLanguage()->getCode(),
2571 $this->getSkin()->getSkinName(),
2573 null, // version; not determined yet
2574 ResourceLoader
::inDebugMode(),
2575 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2576 $this->isPrintable(),
2577 $this->getRequest()->getBool( 'handheld' ),
2580 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2581 // Extract modules that know they're empty
2582 $emptyModules = array ();
2583 foreach ( $modules as $key => $module ) {
2584 if ( $module->isKnownEmpty( $context ) ) {
2585 $emptyModules[$key] = 'ready';
2586 unset( $modules[$key] );
2589 // Inline empty modules: since they're empty, just mark them as 'ready'
2590 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2591 // If we're only getting the styles, we don't need to do anything for empty modules.
2592 $links .= Html
::inlineScript(
2594 ResourceLoader
::makeLoaderConditionalScript(
2596 ResourceLoader
::makeLoaderStateScript( $emptyModules )
2603 // If there are no modules left, skip this group
2604 if ( $modules === array() ) {
2608 // Inline private modules. These can't be loaded through load.php for security
2609 // reasons, see bug 34907. Note that these modules should be loaded from
2610 // getHeadScripts() before the first loader call. Otherwise other modules can't
2611 // properly use them as dependencies (bug 30914)
2612 if ( $group === 'private' ) {
2613 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2614 $links .= Html
::inlineStyle(
2615 $resourceLoader->makeModuleResponse( $context, $modules )
2618 $links .= Html
::inlineScript(
2619 ResourceLoader
::makeLoaderConditionalScript(
2620 $resourceLoader->makeModuleResponse( $context, $modules )
2627 // Special handling for the user group; because users might change their stuff
2628 // on-wiki like user pages, or user preferences; we need to find the highest
2629 // timestamp of these user-changable modules so we can ensure cache misses on change
2630 // This should NOT be done for the site group (bug 27564) because anons get that too
2631 // and we shouldn't be putting timestamps in Squid-cached HTML
2633 if ( $group === 'user' ) {
2634 // Get the maximum timestamp
2636 foreach ( $modules as $module ) {
2637 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2639 // Add a version parameter so cache will break when things change
2640 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2643 $url = ResourceLoader
::makeLoaderURL(
2644 array_keys( $modules ),
2645 $this->getLanguage()->getCode(),
2646 $this->getSkin()->getSkinName(),
2649 ResourceLoader
::inDebugMode(),
2650 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2651 $this->isPrintable(),
2652 $this->getRequest()->getBool( 'handheld' ),
2655 if ( $useESI && $wgResourceLoaderUseESI ) {
2656 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2657 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2658 $link = Html
::inlineStyle( $esi );
2660 $link = Html
::inlineScript( $esi );
2663 // Automatically select style/script elements
2664 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2665 $link = Html
::linkedStyle( $url );
2666 } else if ( $loadCall ) {
2667 $link = Html
::inlineScript(
2668 ResourceLoader
::makeLoaderConditionalScript(
2669 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2673 $link = Html
::linkedScript( $url );
2677 if( $group == 'noscript' ){
2678 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2680 $links .= $link . "\n";
2687 * JS stuff to put in the <head>. This is the startup module, config
2688 * vars and modules marked with position 'top'
2690 * @return String: HTML fragment
2692 function getHeadScripts() {
2693 global $wgResourceLoaderExperimentalAsyncLoading;
2695 // Startup - this will immediately load jquery and mediawiki modules
2696 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2698 // Load config before anything else
2699 $scripts .= Html
::inlineScript(
2700 ResourceLoader
::makeLoaderConditionalScript(
2701 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2705 // Load embeddable private modules before any loader links
2706 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2707 // in mw.loader.implement() calls and deferred until mw.user is available
2708 $embedScripts = array( 'user.options', 'user.tokens' );
2709 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2711 // Script and Messages "only" requests marked for top inclusion
2712 // Messages should go first
2713 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2714 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2716 // Modules requests - let the client calculate dependencies and batch requests as it likes
2717 // Only load modules that have marked themselves for loading at the top
2718 $modules = $this->getModules( true, 'top' );
2720 $scripts .= Html
::inlineScript(
2721 ResourceLoader
::makeLoaderConditionalScript(
2722 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2727 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2728 $scripts .= $this->getScriptsForBottomQueue( true );
2735 * JS stuff to put at the 'bottom', which can either be the bottom of the <body>
2736 * or the bottom of the <head> depending on $wgResourceLoaderExperimentalAsyncLoading:
2737 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2738 * user preferences, site JS and user JS
2740 * @param $inHead boolean If true, this HTML goes into the <head>, if false it goes into the <body>
2743 function getScriptsForBottomQueue( $inHead ) {
2744 global $wgUseSiteJs, $wgAllowUserJs;
2746 // Script and Messages "only" requests marked for bottom inclusion
2747 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2748 // Messages should go first
2749 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2750 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2751 /* $loadCall = */ $inHead
2753 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2754 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2755 /* $loadCall = */ $inHead
2758 // Modules requests - let the client calculate dependencies and batch requests as it likes
2759 // Only load modules that have marked themselves for loading at the bottom
2760 $modules = $this->getModules( true, 'bottom' );
2762 $scripts .= Html
::inlineScript(
2763 ResourceLoader
::makeLoaderConditionalScript(
2764 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2770 $scripts .= "\n" . $this->mScripts
;
2772 $defaultModules = array();
2774 // Add site JS if enabled
2775 if ( $wgUseSiteJs ) {
2776 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2777 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2779 $defaultModules['site'] = 'loading';
2781 // The wiki is configured to not allow a site module.
2782 $defaultModules['site'] = 'missing';
2785 // Add user JS if enabled
2786 if ( $wgAllowUserJs ) {
2787 if ( $this->getUser()->isLoggedIn() ) {
2788 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2789 # XXX: additional security check/prompt?
2790 // We're on a preview of a JS subpage
2791 // Exclude this page from the user module in case it's in there (bug 26283)
2792 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2793 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2795 // Load the previewed JS
2796 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2797 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2798 // asynchronously and may arrive *after* the inline script here. So the previewed code
2799 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2801 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2802 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2803 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2806 $defaultModules['user'] = 'loading';
2808 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2809 // blocking default gadgets that might depend on it. Although arguably default-enabled
2810 // gadgets should not depend on the user module, it's harmless and less error-prone to
2811 // handle this case.
2812 $defaultModules['user'] = 'ready';
2816 $defaultModules['user'] = 'missing';
2819 // Group JS is only enabled if site JS is enabled.
2820 if ( $wgUseSiteJs ) {
2821 if ( $this->getUser()->isLoggedIn() ) {
2822 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2823 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2825 $defaultModules['user.groups'] = 'loading';
2827 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2828 // avoid blocking gadgets that might depend upon the module.
2829 $defaultModules['user.groups'] = 'ready';
2832 // Site (and group JS) disabled
2833 $defaultModules['user.groups'] = 'missing';
2838 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2839 foreach ( $defaultModules as $m => $state ) {
2840 if ( $state == 'loading' ) {
2841 unset( $defaultModules[$m] );
2845 if ( count( $defaultModules ) > 0 ) {
2846 $loaderInit = Html
::inlineScript(
2847 ResourceLoader
::makeLoaderConditionalScript(
2848 ResourceLoader
::makeLoaderStateScript( $defaultModules )
2852 return $loaderInit . $scripts;
2856 * JS stuff to put at the bottom of the <body>
2859 function getBottomScripts() {
2860 global $wgResourceLoaderExperimentalAsyncLoading;
2861 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2862 return $this->getScriptsForBottomQueue( false );
2869 * Add one or more variables to be set in mw.config in JavaScript.
2871 * @param $key {String|Array} Key or array of key/value pars.
2872 * @param $value {Mixed} [optional] Value of the configuration variable.
2874 public function addJsConfigVars( $keys, $value = null ) {
2875 if ( is_array( $keys ) ) {
2876 foreach ( $keys as $key => $value ) {
2877 $this->mJsConfigVars
[$key] = $value;
2882 $this->mJsConfigVars
[$keys] = $value;
2887 * Get an array containing the variables to be set in mw.config in JavaScript.
2889 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2890 * This is only public until that function is removed. You have been warned.
2892 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2893 * - in other words, page-independent/site-wide variables (without state).
2894 * You will only be adding bloat to the html page and causing page caches to
2895 * have to be purged on configuration changes.
2898 public function getJSVars() {
2899 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2903 $canonicalName = false; # bug 21115
2905 $title = $this->getTitle();
2906 $ns = $title->getNamespace();
2907 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2909 // Get the relevant title so that AJAX features can use the correct page name
2910 // when making API requests from certain special pages (bug 34972).
2911 $relevantTitle = $this->getSkin()->getRelevantTitle();
2913 if ( $ns == NS_SPECIAL
) {
2914 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2915 } elseif ( $this->canUseWikiPage() ) {
2916 $wikiPage = $this->getWikiPage();
2917 $latestRevID = $wikiPage->getLatest();
2918 $pageID = $wikiPage->getId();
2921 $lang = $title->getPageLanguage();
2923 // Pre-process information
2924 $separatorTransTable = $lang->separatorTransformTable();
2925 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2926 $compactSeparatorTransTable = array(
2927 implode( "\t", array_keys( $separatorTransTable ) ),
2928 implode( "\t", $separatorTransTable ),
2930 $digitTransTable = $lang->digitTransformTable();
2931 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2932 $compactDigitTransTable = array(
2933 implode( "\t", array_keys( $digitTransTable ) ),
2934 implode( "\t", $digitTransTable ),
2938 'wgCanonicalNamespace' => $nsname,
2939 'wgCanonicalSpecialPageName' => $canonicalName,
2940 'wgNamespaceNumber' => $title->getNamespace(),
2941 'wgPageName' => $title->getPrefixedDBKey(),
2942 'wgTitle' => $title->getText(),
2943 'wgCurRevisionId' => $latestRevID,
2944 'wgArticleId' => $pageID,
2945 'wgIsArticle' => $this->isArticle(),
2946 'wgAction' => Action
::getActionName( $this->getContext() ),
2947 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2948 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2949 'wgCategories' => $this->getCategories(),
2950 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2951 'wgPageContentLanguage' => $lang->getCode(),
2952 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2953 'wgDigitTransformTable' => $compactDigitTransTable,
2954 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
2956 if ( $wgContLang->hasVariants() ) {
2957 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2959 foreach ( $title->getRestrictionTypes() as $type ) {
2960 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2962 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2963 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2965 if ( $title->isMainPage() ) {
2966 $vars['wgIsMainPage'] = true;
2968 if ( $this->mRedirectedFrom
) {
2969 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBKey();
2972 // Allow extensions to add their custom variables to the mw.config map.
2973 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2974 // page-dependant but site-wide (without state).
2975 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2976 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2978 // Merge in variables from addJsConfigVars last
2979 return array_merge( $vars, $this->mJsConfigVars
);
2983 * To make it harder for someone to slip a user a fake
2984 * user-JavaScript or user-CSS preview, a random token
2985 * is associated with the login session. If it's not
2986 * passed back with the preview request, we won't render
2991 public function userCanPreview() {
2992 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2993 ||
!$this->getRequest()->wasPosted()
2994 ||
!$this->getUser()->matchEditToken(
2995 $this->getRequest()->getVal( 'wpEditToken' ) )
2999 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3003 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3007 * @param $addContentType bool: Whether <meta> specifying content type should be returned
3009 * @return array in format "link name or number => 'link html'".
3011 public function getHeadLinksArray( $addContentType = false ) {
3012 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3013 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3014 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3015 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3016 $wgRightsPage, $wgRightsUrl;
3020 if ( $addContentType ) {
3022 # More succinct than <meta http-equiv=Content-Type>, has the
3024 $tags['meta-charset'] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
3026 $tags['meta-content-type'] = Html
::element( 'meta', array(
3027 'http-equiv' => 'Content-Type',
3028 'content' => "$wgMimeType; charset=UTF-8"
3030 $tags['meta-content-style-type'] = Html
::element( 'meta', array( // bug 15835
3031 'http-equiv' => 'Content-Style-Type',
3032 'content' => 'text/css'
3037 $tags['meta-generator'] = Html
::element( 'meta', array(
3038 'name' => 'generator',
3039 'content' => "MediaWiki $wgVersion",
3042 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3043 if( $p !== 'index,follow' ) {
3044 // http://www.robotstxt.org/wc/meta-user.html
3045 // Only show if it's different from the default robots policy
3046 $tags['meta-robots'] = Html
::element( 'meta', array(
3052 if ( count( $this->mKeywords
) > 0 ) {
3054 "/<.*?" . ">/" => '',
3057 $tags['meta-keywords'] = Html
::element( 'meta', array(
3058 'name' => 'keywords',
3059 'content' => preg_replace(
3060 array_keys( $strip ),
3061 array_values( $strip ),
3062 implode( ',', $this->mKeywords
)
3067 foreach ( $this->mMetatags
as $tag ) {
3068 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3070 $tag[0] = substr( $tag[0], 5 );
3074 $tagName = "meta-{$tag[0]}";
3075 if ( isset( $tags[$tagName] ) ) {
3076 $tagName .= $tag[1];
3078 $tags[$tagName] = Html
::element( 'meta',
3081 'content' => $tag[1]
3086 foreach ( $this->mLinktags
as $tag ) {
3087 $tags[] = Html
::element( 'link', $tag );
3090 # Universal edit button
3091 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3092 $user = $this->getUser();
3093 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3094 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3095 // Original UniversalEditButton
3096 $msg = $this->msg( 'edit' )->text();
3097 $tags['universal-edit-button'] = Html
::element( 'link', array(
3098 'rel' => 'alternate',
3099 'type' => 'application/x-wiki',
3101 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3103 // Alternate edit link
3104 $tags['alternative-edit'] = Html
::element( 'link', array(
3107 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3112 # Generally the order of the favicon and apple-touch-icon links
3113 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3114 # uses whichever one appears later in the HTML source. Make sure
3115 # apple-touch-icon is specified first to avoid this.
3116 if ( $wgAppleTouchIcon !== false ) {
3117 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3120 if ( $wgFavicon !== false ) {
3121 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3124 # OpenSearch description link
3125 $tags['opensearch'] = Html
::element( 'link', array(
3127 'type' => 'application/opensearchdescription+xml',
3128 'href' => wfScript( 'opensearch_desc' ),
3129 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3132 if ( $wgEnableAPI ) {
3133 # Real Simple Discovery link, provides auto-discovery information
3134 # for the MediaWiki API (and potentially additional custom API
3135 # support such as WordPress or Twitter-compatible APIs for a
3136 # blogging extension, etc)
3137 $tags['rsd'] = Html
::element( 'link', array(
3139 'type' => 'application/rsd+xml',
3140 // Output a protocol-relative URL here if $wgServer is protocol-relative
3141 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3142 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3148 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3149 $lang = $this->getTitle()->getPageLanguage();
3150 if ( $lang->hasVariants() ) {
3152 $urlvar = $lang->getURLVariant();
3155 $variants = $lang->getVariants();
3156 foreach ( $variants as $_v ) {
3157 $tags["variant-$_v"] = Html
::element( 'link', array(
3158 'rel' => 'alternate',
3160 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3164 $tags['canonical'] = Html
::element( 'link', array(
3165 'rel' => 'canonical',
3166 'href' => $this->getTitle()->getCanonicalUrl()
3174 if ( $wgRightsPage ) {
3175 $copy = Title
::newFromText( $wgRightsPage );
3178 $copyright = $copy->getLocalURL();
3182 if ( !$copyright && $wgRightsUrl ) {
3183 $copyright = $wgRightsUrl;
3187 $tags['copyright'] = Html
::element( 'link', array(
3188 'rel' => 'copyright',
3189 'href' => $copyright )
3195 foreach( $this->getSyndicationLinks() as $format => $link ) {
3196 # Use the page name for the title. In principle, this could
3197 # lead to issues with having the same name for different feeds
3198 # corresponding to the same page, but we can't avoid that at
3201 $tags[] = $this->feedLink(
3204 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3205 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3209 # Recent changes feed should appear on every page (except recentchanges,
3210 # that would be redundant). Put it after the per-page feed to avoid
3211 # changing existing behavior. It's still available, probably via a
3212 # menu in your browser. Some sites might have a different feed they'd
3213 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3214 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3215 # If so, use it instead.
3216 if ( $wgOverrideSiteFeed ) {
3217 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3218 // Note, this->feedLink escapes the url.
3219 $tags[] = $this->feedLink(
3222 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3225 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3226 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3227 foreach ( $wgAdvertisedFeedTypes as $format ) {
3228 $tags[] = $this->feedLink(
3230 $rctitle->getLocalURL( "feed={$format}" ),
3231 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3241 * @param $addContentType bool: Whether <meta> specifying content type should be returned
3243 * @return string HTML tag links to be put in the header.
3245 public function getHeadLinks( $unused = null, $addContentType = false ) {
3246 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3250 * Generate a <link rel/> for a feed.
3252 * @param $type String: feed type
3253 * @param $url String: URL to the feed
3254 * @param $text String: value of the "title" attribute
3255 * @return String: HTML fragment
3257 private function feedLink( $type, $url, $text ) {
3258 return Html
::element( 'link', array(
3259 'rel' => 'alternate',
3260 'type' => "application/$type+xml",
3267 * Add a local or specified stylesheet, with the given media options.
3268 * Meant primarily for internal use...
3270 * @param $style String: URL to the file
3271 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3272 * @param $condition String: for IE conditional comments, specifying an IE version
3273 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3275 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3277 // Even though we expect the media type to be lowercase, but here we
3278 // force it to lowercase to be safe.
3280 $options['media'] = $media;
3283 $options['condition'] = $condition;
3286 $options['dir'] = $dir;
3288 $this->styles
[$style] = $options;
3292 * Adds inline CSS styles
3293 * @param $style_css Mixed: inline CSS
3294 * @param $flip String: Set to 'flip' to flip the CSS if needed
3296 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3297 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3298 # If wanted, and the interface is right-to-left, flip the CSS
3299 $style_css = CSSJanus
::transform( $style_css, true, false );
3301 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3305 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3306 * These will be applied to various media & IE conditionals.
3310 public function buildCssLinks() {
3311 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3312 $wgLang, $wgContLang;
3314 $this->getSkin()->setupSkinUserCss( $this );
3316 // Add ResourceLoader styles
3317 // Split the styles into four groups
3318 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3319 $otherTags = ''; // Tags to append after the normal <link> tags
3320 $resourceLoader = $this->getResourceLoader();
3322 $moduleStyles = $this->getModuleStyles();
3324 // Per-site custom styles
3325 if ( $wgUseSiteCss ) {
3326 $moduleStyles[] = 'site';
3327 $moduleStyles[] = 'noscript';
3328 if( $this->getUser()->isLoggedIn() ){
3329 $moduleStyles[] = 'user.groups';
3333 // Per-user custom styles
3334 if ( $wgAllowUserCss ) {
3335 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3336 // We're on a preview of a CSS subpage
3337 // Exclude this page from the user module in case it's in there (bug 26283)
3338 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3339 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3342 // Load the previewed CSS
3343 // If needed, Janus it first. This is user-supplied CSS, so it's
3344 // assumed to be right for the content language directionality.
3345 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3346 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3347 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3349 $otherTags .= Html
::inlineStyle( $previewedCSS );
3351 // Load the user styles normally
3352 $moduleStyles[] = 'user';
3356 // Per-user preference styles
3357 if ( $wgAllowUserCssPrefs ) {
3358 $moduleStyles[] = 'user.cssprefs';
3361 foreach ( $moduleStyles as $name ) {
3362 $module = $resourceLoader->getModule( $name );
3366 $group = $module->getGroup();
3367 // Modules in groups named "other" or anything different than "user", "site" or "private"
3368 // will be placed in the "other" group
3369 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3372 // We want site, private and user styles to override dynamically added styles from modules, but we want
3373 // dynamically added styles to override statically added styles from other modules. So the order
3374 // has to be other, dynamic, site, private, user
3375 // Add statically added styles for other modules
3376 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3377 // Add normal styles added through addStyle()/addInlineStyle() here
3378 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3379 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3380 // We use a <meta> tag with a made-up name for this because that's valid HTML
3381 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3383 // Add site, private and user styles
3384 // 'private' at present only contains user.options, so put that before 'user'
3385 // Any future private modules will likely have a similar user-specific character
3386 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3387 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3388 ResourceLoaderModule
::TYPE_STYLES
3392 // Add stuff in $otherTags (previewed user CSS if applicable)
3400 public function buildCssLinksArray() {
3403 // Add any extension CSS
3404 foreach ( $this->mExtStyles
as $url ) {
3405 $this->addStyle( $url );
3407 $this->mExtStyles
= array();
3409 foreach( $this->styles
as $file => $options ) {
3410 $link = $this->styleLink( $file, $options );
3412 $links[$file] = $link;
3419 * Generate \<link\> tags for stylesheets
3421 * @param $style String: URL to the file
3422 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3424 * @return String: HTML fragment
3426 protected function styleLink( $style, $options ) {
3427 if( isset( $options['dir'] ) ) {
3428 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3433 if( isset( $options['media'] ) ) {
3434 $media = self
::transformCssMedia( $options['media'] );
3435 if( is_null( $media ) ) {
3442 if( substr( $style, 0, 1 ) == '/' ||
3443 substr( $style, 0, 5 ) == 'http:' ||
3444 substr( $style, 0, 6 ) == 'https:' ) {
3447 global $wgStylePath, $wgStyleVersion;
3448 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3451 $link = Html
::linkedStyle( $url, $media );
3453 if( isset( $options['condition'] ) ) {
3454 $condition = htmlspecialchars( $options['condition'] );
3455 $link = "<!--[if $condition]>$link<![endif]-->";
3461 * Transform "media" attribute based on request parameters
3463 * @param $media String: current value of the "media" attribute
3464 * @return String: modified value of the "media" attribute
3466 public static function transformCssMedia( $media ) {
3467 global $wgRequest, $wgHandheldForIPhone;
3469 // Switch in on-screen display for media testing
3471 'printable' => 'print',
3472 'handheld' => 'handheld',
3474 foreach( $switches as $switch => $targetMedia ) {
3475 if( $wgRequest->getBool( $switch ) ) {
3476 if( $media == $targetMedia ) {
3478 } elseif( $media == 'screen' ) {
3484 // Expand longer media queries as iPhone doesn't grok 'handheld'
3485 if( $wgHandheldForIPhone ) {
3486 $mediaAliases = array(
3487 'screen' => 'screen and (min-device-width: 481px)',
3488 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3491 if( isset( $mediaAliases[$media] ) ) {
3492 $media = $mediaAliases[$media];
3500 * Add a wikitext-formatted message to the output.
3501 * This is equivalent to:
3503 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3505 public function addWikiMsg( /*...*/ ) {
3506 $args = func_get_args();
3507 $name = array_shift( $args );
3508 $this->addWikiMsgArray( $name, $args );
3512 * Add a wikitext-formatted message to the output.
3513 * Like addWikiMsg() except the parameters are taken as an array
3514 * instead of a variable argument list.
3516 * @param $name string
3517 * @param $args array
3519 public function addWikiMsgArray( $name, $args ) {
3520 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3524 * This function takes a number of message/argument specifications, wraps them in
3525 * some overall structure, and then parses the result and adds it to the output.
3527 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3528 * on. The subsequent arguments may either be strings, in which case they are the
3529 * message names, or arrays, in which case the first element is the message name,
3530 * and subsequent elements are the parameters to that message.
3532 * The special named parameter 'options' in a message specification array is passed
3533 * through to the $options parameter of wfMsgExt().
3535 * Don't use this for messages that are not in users interface language.
3539 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3543 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3545 * The newline after opening div is needed in some wikitext. See bug 19226.
3547 * @param $wrap string
3549 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3550 $msgSpecs = func_get_args();
3551 array_shift( $msgSpecs );
3552 $msgSpecs = array_values( $msgSpecs );
3554 foreach ( $msgSpecs as $n => $spec ) {
3556 if ( is_array( $spec ) ) {
3558 $name = array_shift( $args );
3559 if ( isset( $args['options'] ) ) {
3560 $options = $args['options'];
3561 unset( $args['options'] );
3567 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3569 $this->addWikiText( $s );
3573 * Include jQuery core. Use this to avoid loading it multiple times
3574 * before we get a usable script loader.
3576 * @param $modules Array: list of jQuery modules which should be loaded
3577 * @return Array: the list of modules which were not loaded.
3579 * @deprecated since 1.17
3581 public function includeJQuery( $modules = array() ) {