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
23 if ( !defined( 'MEDIAWIKI' ) ) {
28 * This class should be covered by a general architecture document which does
29 * not exist as of January 2011. This is one of the Core classes and should
30 * be read at least once by any new developers.
32 * This class is used to prepare the final rendering. A skin is then
33 * applied to the output parameters (links, javascript, html, categories ...).
35 * @todo FIXME: Another class handles sending the whole page to the client.
37 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
42 class OutputPage
extends ContextSource
{
43 /// Should be private. Used with addMeta() which adds <meta>
44 var $mMetatags = array();
46 /// <meta keywords="stuff"> most of the time the first 10 links to an article
47 var $mKeywords = array();
49 var $mLinktags = array();
51 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
52 var $mExtStyles = array();
54 /// Should be private - has getter and setter. Contains the HTML title
57 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
61 * Holds the debug lines that will be output as comments in page source if
62 * $wgDebugComments is enabled. See also $wgShowDebug.
63 * TODO: make a getter method for this
65 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
67 /// Should be private. Stores contents of <title> tag
70 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
71 var $mIsarticle = false;
74 * Should be private. Has get/set methods properly documented.
75 * Stores "article flag" toggle.
77 var $mIsArticleRelated = true;
80 * Should be private. We have to set isPrintable(). Some pages should
81 * never be printed (ex: redirections).
83 var $mPrintable = false;
86 * Should be private. We have set/get/append methods.
88 * Contains the page subtitle. Special pages usually have some links here.
89 * Don't confuse with site subtitle added by skins.
91 private $mSubtitle = array();
97 * mLastModified and mEtag are used for sending cache control.
98 * The whole caching system should probably be moved into its own class.
100 var $mLastModified = '';
103 * Should be private. No getter but used in sendCacheControl();
104 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
105 * as a unique identifier for the content. It is later used by the client
106 * to compare its cached version with the server version. Client sends
107 * headers If-Match and If-None-Match containing its locally cached ETAG value.
109 * To get more information, you will have to look at HTTP/1.1 protocol which
110 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
114 var $mCategoryLinks = array();
115 var $mCategories = array();
117 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
118 var $mLanguageLinks = array();
121 * Should be private. Used for JavaScript (pre resource loader)
122 * We should split js / css.
123 * mScripts content is inserted as is in <head> by Skin. This might contains
124 * either a link to a stylesheet or inline css.
129 * Inline CSS styles. Use addInlineStyle() sparsingly
131 var $mInlineStyles = '';
137 * Used by skin template.
138 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
140 var $mPageLinkTitle = '';
142 /// Array of elements in <head>. Parser might add its own headers!
143 var $mHeadItems = array();
145 // @todo FIXME: Next variables probably comes from the resource loader
146 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
147 var $mResourceLoader;
148 var $mJsConfigVars = array();
150 /** @todo FIXME: Is this still used ?*/
151 var $mInlineMsg = array();
153 var $mTemplateIds = array();
154 var $mImageTimeKeys = array();
156 var $mRedirectCode = '';
158 var $mFeedLinksAppendQuery = null;
160 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
161 # @see ResourceLoaderModule::$origin
162 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
163 protected $mAllowedModules = array(
164 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
168 * @EasterEgg I just love the name for this self documenting variable.
171 var $mDoNothing = false;
174 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
177 * lazy initialised, use parserOptions()
180 protected $mParserOptions = null;
183 * Handles the atom / rss links.
184 * We probably only support atom in 2011.
185 * Looks like a private variable.
186 * @see $wgAdvertisedFeedTypes
188 var $mFeedLinks = array();
190 // Gwicke work on squid caching? Roughly from 2003.
191 var $mEnableClientCache = true;
194 * Flag if output should only contain the body of the article.
197 var $mArticleBodyOnly = false;
199 var $mNewSectionLink = false;
200 var $mHideNewSectionLink = false;
203 * Comes from the parser. This was probably made to load CSS/JS only
204 * if we had <gallery>. Used directly in CategoryPage.php
205 * Looks like resource loader can replace this.
207 var $mNoGallery = false;
209 // should be private.
210 var $mPageTitleActionText = '';
211 var $mParseWarnings = array();
213 // Cache stuff. Looks like mEnableClientCache
214 var $mSquidMaxage = 0;
217 var $mPreventClickjacking = true;
219 /// should be private. To include the variable {{REVISIONID}}
220 var $mRevisionId = null;
221 private $mRevisionTimestamp = null;
223 var $mFileVersion = null;
226 * An array of stylesheet filenames (relative from skins path), with options
227 * for CSS media, IE conditions, and RTL/LTR direction.
228 * For internal use; add settings in the skin via $this->addStyle()
230 * Style again! This seems like a code duplication since we already have
231 * mStyles. This is what makes OpenSource amazing.
233 var $styles = array();
236 * Whether jQuery is already handled.
238 protected $mJQueryDone = false;
240 private $mIndexPolicy = 'index';
241 private $mFollowPolicy = 'follow';
242 private $mVaryHeader = array(
243 'Accept-Encoding' => array( 'list-contains=gzip' ),
248 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
253 private $mRedirectedFrom = null;
256 * Constructor for OutputPage. This should not be called directly.
257 * Instead a new RequestContext should be created and it will implicitly create
258 * a OutputPage tied to that context.
260 function __construct( IContextSource
$context = null ) {
261 if ( $context === null ) {
262 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
263 wfDeprecated( __METHOD__
);
265 $this->setContext( $context );
270 * Redirect to $url rather than displaying the normal page
272 * @param $url String: URL
273 * @param $responsecode String: HTTP status code
275 public function redirect( $url, $responsecode = '302' ) {
276 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
277 $this->mRedirect
= str_replace( "\n", '', $url );
278 $this->mRedirectCode
= $responsecode;
282 * Get the URL to redirect to, or an empty string if not redirect URL set
286 public function getRedirect() {
287 return $this->mRedirect
;
291 * Set the HTTP status code to send with the output.
293 * @param $statusCode Integer
295 public function setStatusCode( $statusCode ) {
296 $this->mStatusCode
= $statusCode;
300 * Add a new <meta> tag
301 * To add an http-equiv meta tag, precede the name with "http:"
303 * @param $name String tag name
304 * @param $val String tag value
306 function addMeta( $name, $val ) {
307 array_push( $this->mMetatags
, array( $name, $val ) );
311 * Add a keyword or a list of keywords in the page header
313 * @param $text String or array of strings
315 function addKeyword( $text ) {
316 if( is_array( $text ) ) {
317 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
319 array_push( $this->mKeywords
, $text );
324 * Add a new \<link\> tag to the page header
326 * @param $linkarr Array: associative array of attributes.
328 function addLink( $linkarr ) {
329 array_push( $this->mLinktags
, $linkarr );
333 * Add a new \<link\> with "rel" attribute set to "meta"
335 * @param $linkarr Array: associative array mapping attribute names to their
336 * values, both keys and values will be escaped, and the
337 * "rel" attribute will be automatically added
339 function addMetadataLink( $linkarr ) {
340 $linkarr['rel'] = $this->getMetadataAttribute();
341 $this->addLink( $linkarr );
345 * Get the value of the "rel" attribute for metadata links
349 public function getMetadataAttribute() {
350 # note: buggy CC software only reads first "meta" link
351 static $haveMeta = false;
353 return 'alternate meta';
361 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
363 * @param $script String: raw HTML
365 function addScript( $script ) {
366 $this->mScripts
.= $script . "\n";
370 * Register and add a stylesheet from an extension directory.
372 * @param $url String path to sheet. Provide either a full url (beginning
373 * with 'http', etc) or a relative path from the document root
374 * (beginning with '/'). Otherwise it behaves identically to
375 * addStyle() and draws from the /skins folder.
377 public function addExtensionStyle( $url ) {
378 array_push( $this->mExtStyles
, $url );
382 * Get all styles added by extensions
386 function getExtStyle() {
387 return $this->mExtStyles
;
391 * Add a JavaScript file out of skins/common, or a given relative path.
393 * @param $file String: filename in skins/common or complete on-server path
395 * @param $version String: style version of the file. Defaults to $wgStyleVersion
397 public function addScriptFile( $file, $version = null ) {
398 global $wgStylePath, $wgStyleVersion;
399 // See if $file parameter is an absolute URL or begins with a slash
400 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
403 $path = "{$wgStylePath}/common/{$file}";
405 if ( is_null( $version ) )
406 $version = $wgStyleVersion;
407 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
411 * Add a self-contained script tag with the given contents
413 * @param $script String: JavaScript text, no <script> tags
415 public function addInlineScript( $script ) {
416 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
420 * Get all registered JS and CSS tags for the header.
424 function getScript() {
425 return $this->mScripts
. $this->getHeadItems();
429 * Filter an array of modules to remove insufficiently trustworthy members, and modules
430 * which are no longer registered (eg a page is cached before an extension is disabled)
431 * @param $modules Array
432 * @param $position String if not null, only return modules with this position
433 * @param $type string
436 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
437 $resourceLoader = $this->getResourceLoader();
438 $filteredModules = array();
439 foreach( $modules as $val ){
440 $module = $resourceLoader->getModule( $val );
441 if( $module instanceof ResourceLoaderModule
442 && $module->getOrigin() <= $this->getAllowedModules( $type )
443 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
445 $filteredModules[] = $val;
448 return $filteredModules;
452 * Get the list of modules to include on this page
454 * @param $filter Bool whether to filter out insufficiently trustworthy modules
455 * @param $position String if not null, only return modules with this position
456 * @param $param string
457 * @return Array of module names
459 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
460 $modules = array_values( array_unique( $this->$param ) );
462 ?
$this->filterModules( $modules, $position )
467 * Add one or more modules recognized by the resource loader. Modules added
468 * through this function will be loaded by the resource loader when the
471 * @param $modules Mixed: module name (string) or array of module names
473 public function addModules( $modules ) {
474 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
478 * Get the list of module JS to include on this page
483 * @return array of module names
485 public function getModuleScripts( $filter = false, $position = null ) {
486 return $this->getModules( $filter, $position, 'mModuleScripts' );
490 * Add only JS of one or more modules recognized by the resource loader. Module
491 * scripts added through this function will be loaded by the resource loader when
494 * @param $modules Mixed: module name (string) or array of module names
496 public function addModuleScripts( $modules ) {
497 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
501 * Get the list of module CSS to include on this page
506 * @return Array of module names
508 public function getModuleStyles( $filter = false, $position = null ) {
509 return $this->getModules( $filter, $position, 'mModuleStyles' );
513 * Add only CSS of one or more modules recognized by the resource loader. Module
514 * styles added through this function will be loaded by the resource loader when
517 * @param $modules Mixed: module name (string) or array of module names
519 public function addModuleStyles( $modules ) {
520 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
524 * Get the list of module messages to include on this page
529 * @return Array of module names
531 public function getModuleMessages( $filter = false, $position = null ) {
532 return $this->getModules( $filter, $position, 'mModuleMessages' );
536 * Add only messages of one or more modules recognized by the resource loader.
537 * Module messages added through this function will be loaded by the resource
538 * loader when the page loads.
540 * @param $modules Mixed: module name (string) or array of module names
542 public function addModuleMessages( $modules ) {
543 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
547 * Get an array of head items
551 function getHeadItemsArray() {
552 return $this->mHeadItems
;
556 * Get all header items in a string
560 function getHeadItems() {
562 foreach ( $this->mHeadItems
as $item ) {
569 * Add or replace an header item to the output
571 * @param $name String: item name
572 * @param $value String: raw HTML
574 public function addHeadItem( $name, $value ) {
575 $this->mHeadItems
[$name] = $value;
579 * Check if the header item $name is already set
581 * @param $name String: item name
584 public function hasHeadItem( $name ) {
585 return isset( $this->mHeadItems
[$name] );
589 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
591 * @param $tag String: value of "ETag" header
593 function setETag( $tag ) {
598 * Set whether the output should only contain the body of the article,
599 * without any skin, sidebar, etc.
600 * Used e.g. when calling with "action=render".
602 * @param $only Boolean: whether to output only the body of the article
604 public function setArticleBodyOnly( $only ) {
605 $this->mArticleBodyOnly
= $only;
609 * Return whether the output will contain only the body of the article
613 public function getArticleBodyOnly() {
614 return $this->mArticleBodyOnly
;
618 * checkLastModified tells the client to use the client-cached page if
619 * possible. If sucessful, the OutputPage is disabled so that
620 * any future call to OutputPage->output() have no effect.
622 * Side effect: sets mLastModified for Last-Modified header
624 * @param $timestamp string
626 * @return Boolean: true iff cache-ok headers was sent.
628 public function checkLastModified( $timestamp ) {
629 global $wgCachePages, $wgCacheEpoch;
631 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
632 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
635 if( !$wgCachePages ) {
636 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
639 if( $this->getUser()->getOption( 'nocache' ) ) {
640 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
644 $timestamp = wfTimestamp( TS_MW
, $timestamp );
645 $modifiedTimes = array(
646 'page' => $timestamp,
647 'user' => $this->getUser()->getTouched(),
648 'epoch' => $wgCacheEpoch
650 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
652 $maxModified = max( $modifiedTimes );
653 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
655 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
656 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
662 foreach ( $modifiedTimes as $name => $value ) {
663 if ( $info !== '' ) {
666 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
669 # IE sends sizes after the date like this:
670 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
671 # this breaks strtotime().
672 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
674 wfSuppressWarnings(); // E_STRICT system time bitching
675 $clientHeaderTime = strtotime( $clientHeader );
677 if ( !$clientHeaderTime ) {
678 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
681 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
683 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
684 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
685 wfDebug( __METHOD__
. ": effective Last-Modified: " .
686 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
687 if( $clientHeaderTime < $maxModified ) {
688 wfDebug( __METHOD__
. ": STALE, $info\n", false );
693 # Give a 304 response code and disable body output
694 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
695 ini_set( 'zlib.output_compression', 0 );
696 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
697 $this->sendCacheControl();
700 // Don't output a compressed blob when using ob_gzhandler;
701 // it's technically against HTTP spec and seems to confuse
702 // Firefox when the response gets split over two packets.
703 wfClearOutputBuffers();
709 * Override the last modified timestamp
711 * @param $timestamp String: new timestamp, in a format readable by
714 public function setLastModified( $timestamp ) {
715 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
719 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
721 * @param $policy String: the literal string to output as the contents of
722 * the meta tag. Will be parsed according to the spec and output in
726 public function setRobotPolicy( $policy ) {
727 $policy = Article
::formatRobotPolicy( $policy );
729 if( isset( $policy['index'] ) ) {
730 $this->setIndexPolicy( $policy['index'] );
732 if( isset( $policy['follow'] ) ) {
733 $this->setFollowPolicy( $policy['follow'] );
738 * Set the index policy for the page, but leave the follow policy un-
741 * @param $policy string Either 'index' or 'noindex'.
744 public function setIndexPolicy( $policy ) {
745 $policy = trim( $policy );
746 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
747 $this->mIndexPolicy
= $policy;
752 * Set the follow policy for the page, but leave the index policy un-
755 * @param $policy String: either 'follow' or 'nofollow'.
758 public function setFollowPolicy( $policy ) {
759 $policy = trim( $policy );
760 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
761 $this->mFollowPolicy
= $policy;
766 * Set the new value of the "action text", this will be added to the
767 * "HTML title", separated from it with " - ".
769 * @param $text String: new value of the "action text"
771 public function setPageTitleActionText( $text ) {
772 $this->mPageTitleActionText
= $text;
776 * Get the value of the "action text"
780 public function getPageTitleActionText() {
781 if ( isset( $this->mPageTitleActionText
) ) {
782 return $this->mPageTitleActionText
;
787 * "HTML title" means the contents of <title>.
788 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
790 * @param $name string
792 public function setHTMLTitle( $name ) {
793 if ( $name instanceof Message
) {
794 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
796 $this->mHTMLtitle
= $name;
801 * Return the "HTML title", i.e. the content of the <title> tag.
805 public function getHTMLTitle() {
806 return $this->mHTMLtitle
;
810 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
814 public function setRedirectedFrom( $t ) {
815 $this->mRedirectedFrom
= $t;
819 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
820 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
821 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
822 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
824 * @param $name string|Message
826 public function setPageTitle( $name ) {
827 if ( $name instanceof Message
) {
828 $name = $name->setContext( $this->getContext() )->text();
831 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
832 # but leave "<i>foobar</i>" alone
833 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
834 $this->mPagetitle
= $nameWithTags;
836 # change "<i>foo&bar</i>" to "foo&bar"
837 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
841 * Return the "page title", i.e. the content of the \<h1\> tag.
845 public function getPageTitle() {
846 return $this->mPagetitle
;
850 * Set the Title object to use
852 * @param $t Title object
854 public function setTitle( Title
$t ) {
855 $this->getContext()->setTitle( $t );
860 * Replace the subtile with $str
862 * @param $str String|Message: new value of the subtitle
864 public function setSubtitle( $str ) {
865 $this->clearSubtitle();
866 $this->addSubtitle( $str );
870 * Add $str to the subtitle
872 * @deprecated in 1.19; use addSubtitle() instead
873 * @param $str String|Message to add to the subtitle
875 public function appendSubtitle( $str ) {
876 $this->addSubtitle( $str );
880 * Add $str to the subtitle
882 * @param $str String|Message to add to the subtitle
884 public function addSubtitle( $str ) {
885 if ( $str instanceof Message
) {
886 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
888 $this->mSubtitle
[] = $str;
893 * Add a subtitle containing a backlink to a page
895 * @param $title Title to link to
897 public function addBacklinkSubtitle( Title
$title ) {
899 if ( $title->isRedirect() ) {
900 $query['redirect'] = 'no';
902 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
906 * Clear the subtitles
908 public function clearSubtitle() {
909 $this->mSubtitle
= array();
917 public function getSubtitle() {
918 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
922 * Set the page as printable, i.e. it'll be displayed with with all
923 * print styles included
925 public function setPrintable() {
926 $this->mPrintable
= true;
930 * Return whether the page is "printable"
934 public function isPrintable() {
935 return $this->mPrintable
;
939 * Disable output completely, i.e. calling output() will have no effect
941 public function disable() {
942 $this->mDoNothing
= true;
946 * Return whether the output will be completely disabled
950 public function isDisabled() {
951 return $this->mDoNothing
;
955 * Show an "add new section" link?
959 public function showNewSectionLink() {
960 return $this->mNewSectionLink
;
964 * Forcibly hide the new section link?
968 public function forceHideNewSectionLink() {
969 return $this->mHideNewSectionLink
;
973 * Add or remove feed links in the page header
974 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
975 * for the new version
978 * @param $show Boolean: true: add default feeds, false: remove all feeds
980 public function setSyndicated( $show = true ) {
982 $this->setFeedAppendQuery( false );
984 $this->mFeedLinks
= array();
989 * Add default feeds to the page header
990 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
991 * for the new version
994 * @param $val String: query to append to feed links or false to output
997 public function setFeedAppendQuery( $val ) {
998 global $wgAdvertisedFeedTypes;
1000 $this->mFeedLinks
= array();
1002 foreach ( $wgAdvertisedFeedTypes as $type ) {
1003 $query = "feed=$type";
1004 if ( is_string( $val ) ) {
1005 $query .= '&' . $val;
1007 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1012 * Add a feed link to the page header
1014 * @param $format String: feed type, should be a key of $wgFeedClasses
1015 * @param $href String: URL
1017 public function addFeedLink( $format, $href ) {
1018 global $wgAdvertisedFeedTypes;
1020 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1021 $this->mFeedLinks
[$format] = $href;
1026 * Should we output feed links for this page?
1029 public function isSyndicated() {
1030 return count( $this->mFeedLinks
) > 0;
1034 * Return URLs for each supported syndication format for this page.
1035 * @return array associating format keys with URLs
1037 public function getSyndicationLinks() {
1038 return $this->mFeedLinks
;
1042 * Will currently always return null
1046 public function getFeedAppendQuery() {
1047 return $this->mFeedLinksAppendQuery
;
1051 * Set whether the displayed content is related to the source of the
1052 * corresponding article on the wiki
1053 * Setting true will cause the change "article related" toggle to true
1057 public function setArticleFlag( $v ) {
1058 $this->mIsarticle
= $v;
1060 $this->mIsArticleRelated
= $v;
1065 * Return whether the content displayed page is related to the source of
1066 * the corresponding article on the wiki
1070 public function isArticle() {
1071 return $this->mIsarticle
;
1075 * Set whether this page is related an article on the wiki
1076 * Setting false will cause the change of "article flag" toggle to false
1080 public function setArticleRelated( $v ) {
1081 $this->mIsArticleRelated
= $v;
1083 $this->mIsarticle
= false;
1088 * Return whether this page is related an article on the wiki
1092 public function isArticleRelated() {
1093 return $this->mIsArticleRelated
;
1097 * Add new language links
1099 * @param $newLinkArray array Associative array mapping language code to the page
1102 public function addLanguageLinks( $newLinkArray ) {
1103 $this->mLanguageLinks +
= $newLinkArray;
1107 * Reset the language links and add new language links
1109 * @param $newLinkArray array Associative array mapping language code to the page
1112 public function setLanguageLinks( $newLinkArray ) {
1113 $this->mLanguageLinks
= $newLinkArray;
1117 * Get the list of language links
1119 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1121 public function getLanguageLinks() {
1122 return $this->mLanguageLinks
;
1126 * Add an array of categories, with names in the keys
1128 * @param $categories Array mapping category name => sort key
1130 public function addCategoryLinks( $categories ) {
1133 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1137 # Add the links to a LinkBatch
1138 $arr = array( NS_CATEGORY
=> $categories );
1139 $lb = new LinkBatch
;
1140 $lb->setArray( $arr );
1142 # Fetch existence plus the hiddencat property
1143 $dbr = wfGetDB( DB_SLAVE
);
1144 $res = $dbr->select( array( 'page', 'page_props' ),
1145 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1146 $lb->constructSet( 'page', $dbr ),
1149 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1152 # Add the results to the link cache
1153 $lb->addResultToCache( LinkCache
::singleton(), $res );
1155 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1156 $categories = array_combine(
1157 array_keys( $categories ),
1158 array_fill( 0, count( $categories ), 'normal' )
1161 # Mark hidden categories
1162 foreach ( $res as $row ) {
1163 if ( isset( $row->pp_value
) ) {
1164 $categories[$row->page_title
] = 'hidden';
1168 # Add the remaining categories to the skin
1169 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1170 foreach ( $categories as $category => $type ) {
1171 $origcategory = $category;
1172 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1173 $wgContLang->findVariantLink( $category, $title, true );
1174 if ( $category != $origcategory ) {
1175 if ( array_key_exists( $category, $categories ) ) {
1179 $text = $wgContLang->convertHtml( $title->getText() );
1180 $this->mCategories
[] = $title->getText();
1181 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1187 * Reset the category links (but not the category list) and add $categories
1189 * @param $categories Array mapping category name => sort key
1191 public function setCategoryLinks( $categories ) {
1192 $this->mCategoryLinks
= array();
1193 $this->addCategoryLinks( $categories );
1197 * Get the list of category links, in a 2-D array with the following format:
1198 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1199 * hidden categories) and $link a HTML fragment with a link to the category
1204 public function getCategoryLinks() {
1205 return $this->mCategoryLinks
;
1209 * Get the list of category names this page belongs to
1211 * @return Array of strings
1213 public function getCategories() {
1214 return $this->mCategories
;
1218 * Do not allow scripts which can be modified by wiki users to load on this page;
1219 * only allow scripts bundled with, or generated by, the software.
1221 public function disallowUserJs() {
1222 $this->reduceAllowedModules(
1223 ResourceLoaderModule
::TYPE_SCRIPTS
,
1224 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1229 * Return whether user JavaScript is allowed for this page
1230 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1231 * trustworthiness is identified and enforced automagically.
1232 * Will be removed in 1.20.
1235 public function isUserJsAllowed() {
1236 wfDeprecated( __METHOD__
, '1.18' );
1237 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1241 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1242 * @see ResourceLoaderModule::$origin
1243 * @param $type String ResourceLoaderModule TYPE_ constant
1244 * @return Int ResourceLoaderModule ORIGIN_ class constant
1246 public function getAllowedModules( $type ){
1247 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1248 return min( array_values( $this->mAllowedModules
) );
1250 return isset( $this->mAllowedModules
[$type] )
1251 ?
$this->mAllowedModules
[$type]
1252 : ResourceLoaderModule
::ORIGIN_ALL
;
1257 * Set the highest level of CSS/JS untrustworthiness allowed
1258 * @param $type String ResourceLoaderModule TYPE_ constant
1259 * @param $level Int ResourceLoaderModule class constant
1261 public function setAllowedModules( $type, $level ){
1262 $this->mAllowedModules
[$type] = $level;
1266 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1267 * @param $type String
1268 * @param $level Int ResourceLoaderModule class constant
1270 public function reduceAllowedModules( $type, $level ){
1271 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1275 * Prepend $text to the body HTML
1277 * @param $text String: HTML
1279 public function prependHTML( $text ) {
1280 $this->mBodytext
= $text . $this->mBodytext
;
1284 * Append $text to the body HTML
1286 * @param $text String: HTML
1288 public function addHTML( $text ) {
1289 $this->mBodytext
.= $text;
1293 * Shortcut for adding an Html::element via addHTML.
1297 * @param $element string
1298 * @param $attribs array
1299 * @param $contents string
1301 public function addElement( $element, $attribs = array(), $contents = '' ) {
1302 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1306 * Clear the body HTML
1308 public function clearHTML() {
1309 $this->mBodytext
= '';
1315 * @return String: HTML
1317 public function getHTML() {
1318 return $this->mBodytext
;
1322 * Add $text to the debug output
1324 * @param $text String: debug text
1326 public function debug( $text ) {
1327 $this->mDebugtext
.= $text;
1331 * Get/set the ParserOptions object to use for wikitext parsing
1333 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1334 * current ParserOption object
1335 * @return ParserOptions object
1337 public function parserOptions( $options = null ) {
1338 if ( !$this->mParserOptions
) {
1339 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1340 $this->mParserOptions
->setEditSection( false );
1342 return wfSetVar( $this->mParserOptions
, $options );
1346 * Set the revision ID which will be seen by the wiki text parser
1347 * for things such as embedded {{REVISIONID}} variable use.
1349 * @param $revid Mixed: an positive integer, or null
1350 * @return Mixed: previous value
1352 public function setRevisionId( $revid ) {
1353 $val = is_null( $revid ) ?
null : intval( $revid );
1354 return wfSetVar( $this->mRevisionId
, $val );
1358 * Get the displayed revision ID
1362 public function getRevisionId() {
1363 return $this->mRevisionId
;
1367 * Set the timestamp of the revision which will be displayed. This is used
1368 * to avoid a extra DB call in Skin::lastModified().
1370 * @param $revid Mixed: string, or null
1371 * @return Mixed: previous value
1373 public function setRevisionTimestamp( $timestmap ) {
1374 return wfSetVar( $this->mRevisionTimestamp
, $timestmap );
1378 * Get the timestamp of displayed revision.
1379 * This will be null if not filled by setRevisionTimestamp().
1381 * @return String or null
1383 public function getRevisionTimestamp() {
1384 return $this->mRevisionTimestamp
;
1388 * Set the displayed file version
1390 * @param $file File|bool
1391 * @return Mixed: previous value
1393 public function setFileVersion( $file ) {
1395 if ( $file instanceof File
&& $file->exists() ) {
1396 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1398 return wfSetVar( $this->mFileVersion
, $val, true );
1402 * Get the displayed file version
1404 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1406 public function getFileVersion() {
1407 return $this->mFileVersion
;
1411 * Get the templates used on this page
1413 * @return Array (namespace => dbKey => revId)
1416 public function getTemplateIds() {
1417 return $this->mTemplateIds
;
1421 * Get the files used on this page
1423 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1426 public function getFileSearchOptions() {
1427 return $this->mImageTimeKeys
;
1431 * Convert wikitext to HTML and add it to the buffer
1432 * Default assumes that the current page title will be used.
1434 * @param $text String
1435 * @param $linestart Boolean: is this the start of a line?
1436 * @param $interface Boolean: is this text in the user interface language?
1438 public function addWikiText( $text, $linestart = true, $interface = true ) {
1439 $title = $this->getTitle(); // Work arround E_STRICT
1440 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1444 * Add wikitext with a custom Title object
1446 * @param $text String: wikitext
1447 * @param $title Title object
1448 * @param $linestart Boolean: is this the start of a line?
1450 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1451 $this->addWikiTextTitle( $text, $title, $linestart );
1455 * Add wikitext with a custom Title object and tidy enabled.
1457 * @param $text String: wikitext
1458 * @param $title Title object
1459 * @param $linestart Boolean: is this the start of a line?
1461 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1462 $this->addWikiTextTitle( $text, $title, $linestart, true );
1466 * Add wikitext with tidy enabled
1468 * @param $text String: wikitext
1469 * @param $linestart Boolean: is this the start of a line?
1471 public function addWikiTextTidy( $text, $linestart = true ) {
1472 $title = $this->getTitle();
1473 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1477 * Add wikitext with a custom Title object
1479 * @param $text String: wikitext
1480 * @param $title Title object
1481 * @param $linestart Boolean: is this the start of a line?
1482 * @param $tidy Boolean: whether to use tidy
1483 * @param $interface Boolean: whether it is an interface message
1484 * (for example disables conversion)
1486 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1489 wfProfileIn( __METHOD__
);
1491 $popts = $this->parserOptions();
1492 $oldTidy = $popts->setTidy( $tidy );
1493 $popts->setInterfaceMessage( (bool) $interface );
1495 $parserOutput = $wgParser->parse(
1496 $text, $title, $popts,
1497 $linestart, true, $this->mRevisionId
1500 $popts->setTidy( $oldTidy );
1502 $this->addParserOutput( $parserOutput );
1504 wfProfileOut( __METHOD__
);
1508 * Add a ParserOutput object, but without Html
1510 * @param $parserOutput ParserOutput object
1512 public function addParserOutputNoText( &$parserOutput ) {
1513 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1514 $this->addCategoryLinks( $parserOutput->getCategories() );
1515 $this->mNewSectionLink
= $parserOutput->getNewSection();
1516 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1518 $this->mParseWarnings
= $parserOutput->getWarnings();
1519 if ( !$parserOutput->isCacheable() ) {
1520 $this->enableClientCache( false );
1522 $this->mNoGallery
= $parserOutput->getNoGallery();
1523 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1524 $this->addModules( $parserOutput->getModules() );
1525 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1526 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1527 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1529 // Template versioning...
1530 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1531 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1532 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1534 $this->mTemplateIds
[$ns] = $dbks;
1537 // File versioning...
1538 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1539 $this->mImageTimeKeys
[$dbk] = $data;
1542 // Hooks registered in the object
1543 global $wgParserOutputHooks;
1544 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1545 list( $hookName, $data ) = $hookInfo;
1546 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1547 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1551 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1555 * Add a ParserOutput object
1557 * @param $parserOutput ParserOutput
1559 function addParserOutput( &$parserOutput ) {
1560 $this->addParserOutputNoText( $parserOutput );
1561 $text = $parserOutput->getText();
1562 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1563 $this->addHTML( $text );
1568 * Add the output of a QuickTemplate to the output buffer
1570 * @param $template QuickTemplate
1572 public function addTemplate( &$template ) {
1574 $template->execute();
1575 $this->addHTML( ob_get_contents() );
1580 * Parse wikitext and return the HTML.
1582 * @param $text String
1583 * @param $linestart Boolean: is this the start of a line?
1584 * @param $interface Boolean: use interface language ($wgLang instead of
1585 * $wgContLang) while parsing language sensitive magic
1586 * words like GRAMMAR and PLURAL. This also disables
1587 * LanguageConverter.
1588 * @param $language Language object: target language object, will override
1590 * @return String: HTML
1592 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1595 if( is_null( $this->getTitle() ) ) {
1596 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1599 $popts = $this->parserOptions();
1601 $popts->setInterfaceMessage( true );
1603 if ( $language !== null ) {
1604 $oldLang = $popts->setTargetLanguage( $language );
1607 $parserOutput = $wgParser->parse(
1608 $text, $this->getTitle(), $popts,
1609 $linestart, true, $this->mRevisionId
1613 $popts->setInterfaceMessage( false );
1615 if ( $language !== null ) {
1616 $popts->setTargetLanguage( $oldLang );
1619 return $parserOutput->getText();
1623 * Parse wikitext, strip paragraphs, and return the HTML.
1625 * @param $text String
1626 * @param $linestart Boolean: is this the start of a line?
1627 * @param $interface Boolean: use interface language ($wgLang instead of
1628 * $wgContLang) while parsing language sensitive magic
1629 * words like GRAMMAR and PLURAL
1630 * @return String: HTML
1632 public function parseInline( $text, $linestart = true, $interface = false ) {
1633 $parsed = $this->parse( $text, $linestart, $interface );
1636 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1644 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1646 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1648 public function setSquidMaxage( $maxage ) {
1649 $this->mSquidMaxage
= $maxage;
1653 * Use enableClientCache(false) to force it to send nocache headers
1655 * @param $state bool
1659 public function enableClientCache( $state ) {
1660 return wfSetVar( $this->mEnableClientCache
, $state );
1664 * Get the list of cookies that will influence on the cache
1668 function getCacheVaryCookies() {
1669 global $wgCookiePrefix, $wgCacheVaryCookies;
1671 if ( $cookies === null ) {
1672 $cookies = array_merge(
1674 "{$wgCookiePrefix}Token",
1675 "{$wgCookiePrefix}LoggedOut",
1680 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1686 * Check if the request has a cache-varying cookie header
1687 * If it does, it's very important that we don't allow public caching
1691 function haveCacheVaryCookies() {
1692 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1693 if ( $cookieHeader === false ) {
1696 $cvCookies = $this->getCacheVaryCookies();
1697 foreach ( $cvCookies as $cookieName ) {
1698 # Check for a simple string match, like the way squid does it
1699 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1700 wfDebug( __METHOD__
. ": found $cookieName\n" );
1704 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1709 * Add an HTTP header that will influence on the cache
1711 * @param $header String: header name
1712 * @param $option Array|null
1713 * @todo FIXME: Document the $option parameter; it appears to be for
1714 * X-Vary-Options but what format is acceptable?
1716 public function addVaryHeader( $header, $option = null ) {
1717 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1718 $this->mVaryHeader
[$header] = (array)$option;
1719 } elseif( is_array( $option ) ) {
1720 if( is_array( $this->mVaryHeader
[$header] ) ) {
1721 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1723 $this->mVaryHeader
[$header] = $option;
1726 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1730 * Get a complete X-Vary-Options header
1734 public function getXVO() {
1735 $cvCookies = $this->getCacheVaryCookies();
1737 $cookiesOption = array();
1738 foreach ( $cvCookies as $cookieName ) {
1739 $cookiesOption[] = 'string-contains=' . $cookieName;
1741 $this->addVaryHeader( 'Cookie', $cookiesOption );
1744 foreach( $this->mVaryHeader
as $header => $option ) {
1745 $newheader = $header;
1746 if( is_array( $option ) ) {
1747 $newheader .= ';' . implode( ';', $option );
1749 $headers[] = $newheader;
1751 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1757 * bug 21672: Add Accept-Language to Vary and XVO headers
1758 * if there's no 'variant' parameter existed in GET.
1761 * /w/index.php?title=Main_page should always be served; but
1762 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1764 function addAcceptLanguage() {
1765 $lang = $this->getTitle()->getPageLanguage();
1766 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1767 $variants = $lang->getVariants();
1768 $aloption = array();
1769 foreach ( $variants as $variant ) {
1770 if( $variant === $lang->getCode() ) {
1773 $aloption[] = 'string-contains=' . $variant;
1775 // IE and some other browsers use another form of language code
1776 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1777 // We should handle these too.
1778 $ievariant = explode( '-', $variant );
1779 if ( count( $ievariant ) == 2 ) {
1780 $ievariant[1] = strtoupper( $ievariant[1] );
1781 $ievariant = implode( '-', $ievariant );
1782 $aloption[] = 'string-contains=' . $ievariant;
1786 $this->addVaryHeader( 'Accept-Language', $aloption );
1791 * Set a flag which will cause an X-Frame-Options header appropriate for
1792 * edit pages to be sent. The header value is controlled by
1793 * $wgEditPageFrameOptions.
1795 * This is the default for special pages. If you display a CSRF-protected
1796 * form on an ordinary view page, then you need to call this function.
1798 * @param $enable bool
1800 public function preventClickjacking( $enable = true ) {
1801 $this->mPreventClickjacking
= $enable;
1805 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1806 * This can be called from pages which do not contain any CSRF-protected
1809 public function allowClickjacking() {
1810 $this->mPreventClickjacking
= false;
1814 * Get the X-Frame-Options header value (without the name part), or false
1815 * if there isn't one. This is used by Skin to determine whether to enable
1816 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1820 public function getFrameOptions() {
1821 global $wgBreakFrames, $wgEditPageFrameOptions;
1822 if ( $wgBreakFrames ) {
1824 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1825 return $wgEditPageFrameOptions;
1831 * Send cache control HTTP headers
1833 public function sendCacheControl() {
1834 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1836 $response = $this->getRequest()->response();
1837 if ( $wgUseETag && $this->mETag
) {
1838 $response->header( "ETag: $this->mETag" );
1841 $this->addAcceptLanguage();
1843 # don't serve compressed data to clients who can't handle it
1844 # maintain different caches for logged-in users and non-logged in ones
1845 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1848 # Add an X-Vary-Options header for Squid with Wikimedia patches
1849 $response->header( $this->getXVO() );
1852 if( $this->mEnableClientCache
) {
1854 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1855 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1859 # We'll purge the proxy cache explicitly, but require end user agents
1860 # to revalidate against the proxy on each visit.
1861 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1862 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1863 # start with a shorter timeout for initial testing
1864 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1865 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1866 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1868 # We'll purge the proxy cache for anons explicitly, but require end user agents
1869 # to revalidate against the proxy on each visit.
1870 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1871 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1872 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1873 # start with a shorter timeout for initial testing
1874 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1875 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1878 # We do want clients to cache if they can, but they *must* check for updates
1879 # on revisiting the page.
1880 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1881 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1882 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1884 if($this->mLastModified
) {
1885 $response->header( "Last-Modified: {$this->mLastModified}" );
1888 wfDebug( __METHOD__
. ": no caching **\n", false );
1890 # In general, the absence of a last modified header should be enough to prevent
1891 # the client from using its cache. We send a few other things just to make sure.
1892 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1893 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1894 $response->header( 'Pragma: no-cache' );
1899 * Get the message associed with the HTTP response code $code
1901 * @param $code Integer: status code
1902 * @return String or null: message or null if $code is not in the list of
1905 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1907 public static function getStatusMessage( $code ) {
1908 wfDeprecated( __METHOD__
);
1909 return HttpStatus
::getMessage( $code );
1913 * Finally, all the text has been munged and accumulated into
1914 * the object, let's actually output it:
1916 public function output() {
1917 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1919 if( $this->mDoNothing
) {
1923 wfProfileIn( __METHOD__
);
1925 $response = $this->getRequest()->response();
1927 if ( $this->mRedirect
!= '' ) {
1928 # Standards require redirect URLs to be absolute
1929 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1931 $redirect = $this->mRedirect
;
1932 $code = $this->mRedirectCode
;
1934 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1935 if( $code == '301' ||
$code == '303' ) {
1936 if( !$wgDebugRedirects ) {
1937 $message = HttpStatus
::getMessage( $code );
1938 $response->header( "HTTP/1.1 $code $message" );
1940 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1942 if ( $wgVaryOnXFP ) {
1943 $this->addVaryHeader( 'X-Forwarded-Proto' );
1945 $this->sendCacheControl();
1947 $response->header( "Content-Type: text/html; charset=utf-8" );
1948 if( $wgDebugRedirects ) {
1949 $url = htmlspecialchars( $redirect );
1950 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1951 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1952 print "</body>\n</html>\n";
1954 $response->header( 'Location: ' . $redirect );
1958 wfProfileOut( __METHOD__
);
1960 } elseif ( $this->mStatusCode
) {
1961 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1963 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1967 # Buffer output; final headers may depend on later processing
1970 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1971 $response->header( 'Content-language: ' . $wgLanguageCode );
1973 // Prevent framing, if requested
1974 $frameOptions = $this->getFrameOptions();
1975 if ( $frameOptions ) {
1976 $response->header( "X-Frame-Options: $frameOptions" );
1979 if ( $this->mArticleBodyOnly
) {
1980 $this->out( $this->mBodytext
);
1982 $this->addDefaultModules();
1984 $sk = $this->getSkin();
1986 // Hook that allows last minute changes to the output page, e.g.
1987 // adding of CSS or Javascript by extensions.
1988 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1990 wfProfileIn( 'Output-skin' );
1992 wfProfileOut( 'Output-skin' );
1995 $this->sendCacheControl();
1997 wfProfileOut( __METHOD__
);
2001 * Actually output something with print().
2003 * @param $ins String: the string to output
2005 public function out( $ins ) {
2010 * Produce a "user is blocked" page.
2011 * @deprecated since 1.18
2013 function blockedPage() {
2014 throw new UserBlockedError( $this->getUser()->mBlock
);
2018 * Prepare this object to display an error page; disable caching and
2019 * indexing, clear the current text and redirect, set the page's title
2020 * and optionally an custom HTML title (content of the <title> tag).
2022 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2023 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2024 * optional, if not passed the <title> attribute will be
2025 * based on $pageTitle
2027 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2028 if ( $this->getTitle() ) {
2029 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
2032 $this->setPageTitle( $pageTitle );
2033 if ( $htmlTitle !== false ) {
2034 $this->setHTMLTitle( $htmlTitle );
2036 $this->setRobotPolicy( 'noindex,nofollow' );
2037 $this->setArticleRelated( false );
2038 $this->enableClientCache( false );
2039 $this->mRedirect
= '';
2040 $this->clearSubtitle();
2045 * Output a standard error page
2047 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2048 * showErrorPage( 'titlemsg', $messageObject );
2050 * @param $title String: message key for page title
2051 * @param $msg Mixed: message key (string) for page text, or a Message object
2052 * @param $params Array: message parameters; ignored if $msg is a Message object
2054 public function showErrorPage( $title, $msg, $params = array() ) {
2055 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2057 if ( $msg instanceof Message
){
2058 $this->addHTML( $msg->parse() );
2060 $this->addWikiMsgArray( $msg, $params );
2063 $this->returnToMain();
2067 * Output a standard permission error page
2069 * @param $errors Array: error message keys
2070 * @param $action String: action that was denied or null if unknown
2072 public function showPermissionsErrorPage( $errors, $action = null ) {
2073 global $wgGroupPermissions;
2075 // For some action (read, edit, create and upload), display a "login to do this action"
2076 // error if all of the following conditions are met:
2077 // 1. the user is not logged in
2078 // 2. the only error is insufficient permissions (i.e. no block or something else)
2079 // 3. the error can be avoided simply by logging in
2080 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2081 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2082 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2083 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2084 ||
( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2086 $displayReturnto = null;
2088 # Due to bug 32276, if a user does not have read permissions,
2089 # $this->getTitle() will just give Special:Badtitle, which is
2090 # not especially useful as a returnto parameter. Use the title
2091 # from the request instead, if there was one.
2092 $request = $this->getRequest();
2093 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2094 if ( $action == 'edit' ) {
2095 $msg = 'whitelistedittext';
2096 $displayReturnto = $returnto;
2097 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2098 $msg = 'nocreatetext';
2099 } elseif ( $action == 'upload' ) {
2100 $msg = 'uploadnologintext';
2102 $msg = 'loginreqpagetext';
2103 $displayReturnto = Title
::newMainPage();
2109 $query['returnto'] = $returnto->getPrefixedText();
2111 if ( !$request->wasPosted() ) {
2112 $returntoquery = $request->getValues();
2113 unset( $returntoquery['title'] );
2114 unset( $returntoquery['returnto'] );
2115 unset( $returntoquery['returntoquery'] );
2116 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2119 $loginLink = Linker
::linkKnown(
2120 SpecialPage
::getTitleFor( 'Userlogin' ),
2121 $this->msg( 'loginreqlink' )->escaped(),
2126 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2127 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2129 # Don't return to a page the user can't read otherwise
2130 # we'll end up in a pointless loop
2131 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2132 $this->returnToMain( null, $displayReturnto );
2135 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2136 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2141 * Display an error page indicating that a given version of MediaWiki is
2142 * required to use it
2144 * @param $version Mixed: the version of MediaWiki needed to use the page
2146 public function versionRequired( $version ) {
2147 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2149 $this->addWikiMsg( 'versionrequiredtext', $version );
2150 $this->returnToMain();
2154 * Display an error page noting that a given permission bit is required.
2155 * @deprecated since 1.18, just throw the exception directly
2156 * @param $permission String: key required
2158 public function permissionRequired( $permission ) {
2159 throw new PermissionsError( $permission );
2163 * Produce the stock "please login to use the wiki" page
2165 * @deprecated in 1.19; throw the exception directly
2167 public function loginToUse() {
2168 throw new PermissionsError( 'read' );
2172 * Format a list of error messages
2174 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2175 * @param $action String: action that was denied or null if unknown
2176 * @return String: the wikitext error-messages, formatted into a list.
2178 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2179 if ( $action == null ) {
2180 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2182 $action_desc = $this->msg( "action-$action" )->plain();
2184 'permissionserrorstext-withaction',
2187 )->plain() . "\n\n";
2190 if ( count( $errors ) > 1 ) {
2191 $text .= '<ul class="permissions-errors">' . "\n";
2193 foreach( $errors as $error ) {
2195 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2200 $text .= "<div class=\"permissions-errors\">\n" .
2201 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2209 * Display a page stating that the Wiki is in read-only mode,
2210 * and optionally show the source of the page that the user
2211 * was trying to edit. Should only be called (for this
2212 * purpose) after wfReadOnly() has returned true.
2214 * For historical reasons, this function is _also_ used to
2215 * show the error message when a user tries to edit a page
2216 * they are not allowed to edit. (Unless it's because they're
2217 * blocked, then we show blockedPage() instead.) In this
2218 * case, the second parameter should be set to true and a list
2219 * of reasons supplied as the third parameter.
2221 * @todo Needs to be split into multiple functions.
2223 * @param $source String: source code to show (or null).
2224 * @param $protected Boolean: is this a permissions error?
2225 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2226 * @param $action String: action that was denied or null if unknown
2228 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2229 $this->setRobotPolicy( 'noindex,nofollow' );
2230 $this->setArticleRelated( false );
2232 // If no reason is given, just supply a default "I can't let you do
2233 // that, Dave" message. Should only occur if called by legacy code.
2234 if ( $protected && empty( $reasons ) ) {
2235 $reasons[] = array( 'badaccess-group0' );
2238 if ( !empty( $reasons ) ) {
2239 // Permissions error
2241 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2242 $this->addBacklinkSubtitle( $this->getTitle() );
2244 $this->setPageTitle( $this->msg( 'badaccess' ) );
2246 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2248 // Wiki is read only
2249 throw new ReadOnlyError
;
2252 // Show source, if supplied
2253 if( is_string( $source ) ) {
2254 $this->addWikiMsg( 'viewsourcetext' );
2256 $pageLang = $this->getTitle()->getPageLanguage();
2258 'id' => 'wpTextbox1',
2259 'name' => 'wpTextbox1',
2260 'cols' => $this->getUser()->getOption( 'cols' ),
2261 'rows' => $this->getUser()->getOption( 'rows' ),
2262 'readonly' => 'readonly',
2263 'lang' => $pageLang->getHtmlCode(),
2264 'dir' => $pageLang->getDir(),
2266 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2268 // Show templates used by this article
2269 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2270 $this->addHTML( "<div class='templatesUsed'>
2276 # If the title doesn't exist, it's fairly pointless to print a return
2277 # link to it. After all, you just tried editing it and couldn't, so
2278 # what's there to do there?
2279 if( $this->getTitle()->exists() ) {
2280 $this->returnToMain( null, $this->getTitle() );
2285 * Turn off regular page output and return an error reponse
2286 * for when rate limiting has triggered.
2288 public function rateLimited() {
2289 throw new ThrottledError
;
2293 * Show a warning about slave lag
2295 * If the lag is higher than $wgSlaveLagCritical seconds,
2296 * then the warning is a bit more obvious. If the lag is
2297 * lower than $wgSlaveLagWarning, then no warning is shown.
2299 * @param $lag Integer: slave lag
2301 public function showLagWarning( $lag ) {
2302 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2303 if( $lag >= $wgSlaveLagWarning ) {
2304 $message = $lag < $wgSlaveLagCritical
2307 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2308 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2312 public function showFatalError( $message ) {
2313 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2315 $this->addHTML( $message );
2318 public function showUnexpectedValueError( $name, $val ) {
2319 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2322 public function showFileCopyError( $old, $new ) {
2323 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2326 public function showFileRenameError( $old, $new ) {
2327 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2330 public function showFileDeleteError( $name ) {
2331 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2334 public function showFileNotFoundError( $name ) {
2335 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2339 * Add a "return to" link pointing to a specified title
2341 * @param $title Title to link
2342 * @param $query String query string
2343 * @param $text String text of the link (input is not escaped)
2345 public function addReturnTo( $title, $query = array(), $text = null ) {
2346 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2347 $link = $this->msg( 'returnto' )->rawParams(
2348 Linker
::link( $title, $text, array(), $query ) )->escaped();
2349 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2353 * Add a "return to" link pointing to a specified title,
2354 * or the title indicated in the request, or else the main page
2357 * @param $returnto Title or String to return to
2358 * @param $returntoquery String: query string for the return to link
2360 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2361 if ( $returnto == null ) {
2362 $returnto = $this->getRequest()->getText( 'returnto' );
2365 if ( $returntoquery == null ) {
2366 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2369 if ( $returnto === '' ) {
2370 $returnto = Title
::newMainPage();
2373 if ( is_object( $returnto ) ) {
2374 $titleObj = $returnto;
2376 $titleObj = Title
::newFromText( $returnto );
2378 if ( !is_object( $titleObj ) ) {
2379 $titleObj = Title
::newMainPage();
2382 $this->addReturnTo( $titleObj, $returntoquery );
2386 * @param $sk Skin The given Skin
2387 * @param $includeStyle Boolean: unused
2388 * @return String: The doctype, opening <html>, and head element.
2390 public function headElement( Skin
$sk, $includeStyle = true ) {
2393 $userdir = $this->getLanguage()->getDir();
2394 $sitedir = $wgContLang->getDir();
2396 if ( $sk->commonPrintStylesheet() ) {
2397 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2400 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2402 if ( $this->getHTMLTitle() == '' ) {
2403 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2406 $openHead = Html
::openElement( 'head' );
2408 # Don't bother with the newline if $head == ''
2409 $ret .= "$openHead\n";
2412 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2414 $ret .= implode( "\n", array(
2415 $this->getHeadLinks( null, true ),
2416 $this->buildCssLinks(),
2417 $this->getHeadScripts(),
2418 $this->getHeadItems()
2421 $closeHead = Html
::closeElement( 'head' );
2423 $ret .= "$closeHead\n";
2426 $bodyAttrs = array();
2428 # Classes for LTR/RTL directionality support
2429 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2431 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2432 # A <body> class is probably not the best way to do this . . .
2433 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2435 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2436 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2437 $bodyAttrs['class'] .= ' action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2439 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2440 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2442 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2448 * Add the default ResourceLoader modules to this object
2450 private function addDefaultModules() {
2451 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2452 $wgAjaxWatch, $wgEnableMWSuggest;
2454 // Add base resources
2455 $this->addModules( array(
2457 'mediawiki.page.startup',
2458 'mediawiki.page.ready',
2460 if ( $wgIncludeLegacyJavaScript ){
2461 $this->addModules( 'mediawiki.legacy.wikibits' );
2464 if ( $wgPreloadJavaScriptMwUtil ) {
2465 $this->addModules( 'mediawiki.util' );
2468 MWDebug
::addModules( $this );
2470 // Add various resources if required
2472 $this->addModules( 'mediawiki.legacy.ajax' );
2474 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2476 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2477 $this->addModules( 'mediawiki.action.watch.ajax' );
2480 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2481 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2485 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2486 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2489 # Crazy edit-on-double-click stuff
2490 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2491 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2496 * Get a ResourceLoader object associated with this OutputPage
2498 * @return ResourceLoader
2500 public function getResourceLoader() {
2501 if ( is_null( $this->mResourceLoader
) ) {
2502 $this->mResourceLoader
= new ResourceLoader();
2504 return $this->mResourceLoader
;
2509 * @param $modules Array/string with the module name(s)
2510 * @param $only String ResourceLoaderModule TYPE_ class constant
2511 * @param $useESI boolean
2512 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2513 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a <script src="..."> tag
2514 * @return string html <script> and <style> tags
2516 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2517 global $wgResourceLoaderUseESI;
2519 if ( !count( $modules ) ) {
2523 if ( count( $modules ) > 1 ) {
2524 // Remove duplicate module requests
2525 $modules = array_unique( (array) $modules );
2526 // Sort module names so requests are more uniform
2529 if ( ResourceLoader
::inDebugMode() ) {
2530 // Recursively call us for every item
2532 foreach ( $modules as $name ) {
2533 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2539 // Create keyed-by-group list of module objects from modules list
2541 $resourceLoader = $this->getResourceLoader();
2542 foreach ( (array) $modules as $name ) {
2543 $module = $resourceLoader->getModule( $name );
2544 # Check that we're allowed to include this module on this page
2546 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2547 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2548 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2549 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2555 $group = $module->getGroup();
2556 if ( !isset( $groups[$group] ) ) {
2557 $groups[$group] = array();
2559 $groups[$group][$name] = $module;
2563 foreach ( $groups as $group => $modules ) {
2564 // Special handling for user-specific groups
2566 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2567 $user = $this->getUser()->getName();
2570 // Create a fake request based on the one we are about to make so modules return
2571 // correct timestamp and emptiness data
2572 $query = ResourceLoader
::makeLoaderQuery(
2573 array(), // modules; not determined yet
2574 $this->getLanguage()->getCode(),
2575 $this->getSkin()->getSkinName(),
2577 null, // version; not determined yet
2578 ResourceLoader
::inDebugMode(),
2579 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2580 $this->isPrintable(),
2581 $this->getRequest()->getBool( 'handheld' ),
2584 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2585 // Extract modules that know they're empty
2586 $emptyModules = array ();
2587 foreach ( $modules as $key => $module ) {
2588 if ( $module->isKnownEmpty( $context ) ) {
2589 $emptyModules[$key] = 'ready';
2590 unset( $modules[$key] );
2593 // Inline empty modules: since they're empty, just mark them as 'ready'
2594 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2595 // If we're only getting the styles, we don't need to do anything for empty modules.
2596 $links .= Html
::inlineScript(
2598 ResourceLoader
::makeLoaderConditionalScript(
2600 ResourceLoader
::makeLoaderStateScript( $emptyModules )
2607 // If there are no modules left, skip this group
2608 if ( $modules === array() ) {
2612 // Inline private modules. These can't be loaded through load.php for security
2613 // reasons, see bug 34907. Note that these modules should be loaded from
2614 // getHeadScripts() before the first loader call. Otherwise other modules can't
2615 // properly use them as dependencies (bug 30914)
2616 if ( $group === 'private' ) {
2617 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2618 $links .= Html
::inlineStyle(
2619 $resourceLoader->makeModuleResponse( $context, $modules )
2622 $links .= Html
::inlineScript(
2623 ResourceLoader
::makeLoaderConditionalScript(
2624 $resourceLoader->makeModuleResponse( $context, $modules )
2631 // Special handling for the user group; because users might change their stuff
2632 // on-wiki like user pages, or user preferences; we need to find the highest
2633 // timestamp of these user-changable modules so we can ensure cache misses on change
2634 // This should NOT be done for the site group (bug 27564) because anons get that too
2635 // and we shouldn't be putting timestamps in Squid-cached HTML
2637 if ( $group === 'user' ) {
2638 // Get the maximum timestamp
2640 foreach ( $modules as $module ) {
2641 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2643 // Add a version parameter so cache will break when things change
2644 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2647 $url = ResourceLoader
::makeLoaderURL(
2648 array_keys( $modules ),
2649 $this->getLanguage()->getCode(),
2650 $this->getSkin()->getSkinName(),
2653 ResourceLoader
::inDebugMode(),
2654 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2655 $this->isPrintable(),
2656 $this->getRequest()->getBool( 'handheld' ),
2659 if ( $useESI && $wgResourceLoaderUseESI ) {
2660 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2661 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2662 $link = Html
::inlineStyle( $esi );
2664 $link = Html
::inlineScript( $esi );
2667 // Automatically select style/script elements
2668 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2669 $link = Html
::linkedStyle( $url );
2670 } else if ( $loadCall ) {
2671 $link = Html
::inlineScript(
2672 ResourceLoader
::makeLoaderConditionalScript(
2673 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2677 $link = Html
::linkedScript( $url );
2681 if( $group == 'noscript' ){
2682 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2684 $links .= $link . "\n";
2691 * JS stuff to put in the <head>. This is the startup module, config
2692 * vars and modules marked with position 'top'
2694 * @return String: HTML fragment
2696 function getHeadScripts() {
2697 global $wgResourceLoaderExperimentalAsyncLoading;
2699 // Startup - this will immediately load jquery and mediawiki modules
2700 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2702 // Load config before anything else
2703 $scripts .= Html
::inlineScript(
2704 ResourceLoader
::makeLoaderConditionalScript(
2705 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2709 // Load embeddable private modules before any loader links
2710 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2711 // in mw.loader.implement() calls and deferred until mw.user is available
2712 $embedScripts = array( 'user.options', 'user.tokens' );
2713 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2715 // Script and Messages "only" requests marked for top inclusion
2716 // Messages should go first
2717 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2718 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2720 // Modules requests - let the client calculate dependencies and batch requests as it likes
2721 // Only load modules that have marked themselves for loading at the top
2722 $modules = $this->getModules( true, 'top' );
2724 $scripts .= Html
::inlineScript(
2725 ResourceLoader
::makeLoaderConditionalScript(
2726 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2731 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2732 $scripts .= $this->getScriptsForBottomQueue( true );
2739 * JS stuff to put at the 'bottom', which can either be the bottom of the <body>
2740 * or the bottom of the <head> depending on $wgResourceLoaderExperimentalAsyncLoading:
2741 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2742 * user preferences, site JS and user JS
2744 * @param $inHead boolean If true, this HTML goes into the <head>, if false it goes into the <body>
2747 function getScriptsForBottomQueue( $inHead ) {
2748 global $wgUseSiteJs, $wgAllowUserJs;
2750 // Script and Messages "only" requests marked for bottom inclusion
2751 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2752 // Messages should go first
2753 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2754 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2755 /* $loadCall = */ $inHead
2757 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2758 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2759 /* $loadCall = */ $inHead
2762 // Modules requests - let the client calculate dependencies and batch requests as it likes
2763 // Only load modules that have marked themselves for loading at the bottom
2764 $modules = $this->getModules( true, 'bottom' );
2766 $scripts .= Html
::inlineScript(
2767 ResourceLoader
::makeLoaderConditionalScript(
2768 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2774 $scripts .= "\n" . $this->mScripts
;
2776 $defaultModules = array();
2778 // Add site JS if enabled
2779 if ( $wgUseSiteJs ) {
2780 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2781 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2783 $defaultModules['site'] = 'loading';
2785 // The wiki is configured to not allow a site module.
2786 $defaultModules['site'] = 'missing';
2789 // Add user JS if enabled
2790 if ( $wgAllowUserJs ) {
2791 if ( $this->getUser()->isLoggedIn() ) {
2792 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2793 # XXX: additional security check/prompt?
2794 // We're on a preview of a JS subpage
2795 // Exclude this page from the user module in case it's in there (bug 26283)
2796 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2797 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2799 // Load the previewed JS
2800 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2801 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2802 // asynchronously and may arrive *after* the inline script here. So the previewed code
2803 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2805 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2806 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2807 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2810 $defaultModules['user'] = 'loading';
2812 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2813 // blocking default gadgets that might depend on it. Although arguably default-enabled
2814 // gadgets should not depend on the user module, it's harmless and less error-prone to
2815 // handle this case.
2816 $defaultModules['user'] = 'ready';
2820 $defaultModules['user'] = 'missing';
2823 // Group JS is only enabled if site JS is enabled.
2824 if ( $wgUseSiteJs ) {
2825 if ( $this->getUser()->isLoggedIn() ) {
2826 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2827 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2829 $defaultModules['user.groups'] = 'loading';
2831 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2832 // avoid blocking gadgets that might depend upon the module.
2833 $defaultModules['user.groups'] = 'ready';
2836 // Site (and group JS) disabled
2837 $defaultModules['user.groups'] = 'missing';
2842 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2843 foreach ( $defaultModules as $m => $state ) {
2844 if ( $state == 'loading' ) {
2845 unset( $defaultModules[$m] );
2849 if ( count( $defaultModules ) > 0 ) {
2850 $loaderInit = Html
::inlineScript(
2851 ResourceLoader
::makeLoaderConditionalScript(
2852 ResourceLoader
::makeLoaderStateScript( $defaultModules )
2856 return $loaderInit . $scripts;
2860 * JS stuff to put at the bottom of the <body>
2863 function getBottomScripts() {
2864 global $wgResourceLoaderExperimentalAsyncLoading;
2865 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2866 return $this->getScriptsForBottomQueue( false );
2873 * Add one or more variables to be set in mw.config in JavaScript.
2875 * @param $key {String|Array} Key or array of key/value pars.
2876 * @param $value {Mixed} [optional] Value of the configuration variable.
2878 public function addJsConfigVars( $keys, $value = null ) {
2879 if ( is_array( $keys ) ) {
2880 foreach ( $keys as $key => $value ) {
2881 $this->mJsConfigVars
[$key] = $value;
2886 $this->mJsConfigVars
[$keys] = $value;
2891 * Get an array containing the variables to be set in mw.config in JavaScript.
2893 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2894 * This is only public until that function is removed. You have been warned.
2896 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2897 * - in other words, page-independent/site-wide variables (without state).
2898 * You will only be adding bloat to the html page and causing page caches to
2899 * have to be purged on configuration changes.
2902 public function getJSVars() {
2903 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2907 $canonicalName = false; # bug 21115
2909 $title = $this->getTitle();
2910 $ns = $title->getNamespace();
2911 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2913 // Get the relevant title so that AJAX features can use the correct page name
2914 // when making API requests from certain special pages (bug 34972).
2915 $relevantTitle = $this->getSkin()->getRelevantTitle();
2917 if ( $ns == NS_SPECIAL
) {
2918 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2919 } elseif ( $this->canUseWikiPage() ) {
2920 $wikiPage = $this->getWikiPage();
2921 $latestRevID = $wikiPage->getLatest();
2922 $pageID = $wikiPage->getId();
2925 $lang = $title->getPageLanguage();
2927 // Pre-process information
2928 $separatorTransTable = $lang->separatorTransformTable();
2929 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2930 $compactSeparatorTransTable = array(
2931 implode( "\t", array_keys( $separatorTransTable ) ),
2932 implode( "\t", $separatorTransTable ),
2934 $digitTransTable = $lang->digitTransformTable();
2935 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2936 $compactDigitTransTable = array(
2937 implode( "\t", array_keys( $digitTransTable ) ),
2938 implode( "\t", $digitTransTable ),
2942 'wgCanonicalNamespace' => $nsname,
2943 'wgCanonicalSpecialPageName' => $canonicalName,
2944 'wgNamespaceNumber' => $title->getNamespace(),
2945 'wgPageName' => $title->getPrefixedDBKey(),
2946 'wgTitle' => $title->getText(),
2947 'wgCurRevisionId' => $latestRevID,
2948 'wgArticleId' => $pageID,
2949 'wgIsArticle' => $this->isArticle(),
2950 'wgAction' => Action
::getActionName( $this->getContext() ),
2951 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2952 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2953 'wgCategories' => $this->getCategories(),
2954 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2955 'wgPageContentLanguage' => $lang->getCode(),
2956 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2957 'wgDigitTransformTable' => $compactDigitTransTable,
2958 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
2960 if ( $wgContLang->hasVariants() ) {
2961 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2963 foreach ( $title->getRestrictionTypes() as $type ) {
2964 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2966 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2967 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2969 if ( $title->isMainPage() ) {
2970 $vars['wgIsMainPage'] = true;
2972 if ( $this->mRedirectedFrom
) {
2973 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBKey();
2976 // Allow extensions to add their custom variables to the mw.config map.
2977 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2978 // page-dependant but site-wide (without state).
2979 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2980 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2982 // Merge in variables from addJsConfigVars last
2983 return array_merge( $vars, $this->mJsConfigVars
);
2987 * To make it harder for someone to slip a user a fake
2988 * user-JavaScript or user-CSS preview, a random token
2989 * is associated with the login session. If it's not
2990 * passed back with the preview request, we won't render
2995 public function userCanPreview() {
2996 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2997 ||
!$this->getRequest()->wasPosted()
2998 ||
!$this->getUser()->matchEditToken(
2999 $this->getRequest()->getVal( 'wpEditToken' ) )
3003 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3007 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3011 * @param $addContentType bool: Whether <meta> specifying content type should be returned
3013 * @return array in format "link name or number => 'link html'".
3015 public function getHeadLinksArray( $addContentType = false ) {
3016 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3017 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3018 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3019 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3020 $wgRightsPage, $wgRightsUrl;
3024 if ( $addContentType ) {
3026 # More succinct than <meta http-equiv=Content-Type>, has the
3028 $tags['meta-charset'] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
3030 $tags['meta-content-type'] = Html
::element( 'meta', array(
3031 'http-equiv' => 'Content-Type',
3032 'content' => "$wgMimeType; charset=UTF-8"
3034 $tags['meta-content-style-type'] = Html
::element( 'meta', array( // bug 15835
3035 'http-equiv' => 'Content-Style-Type',
3036 'content' => 'text/css'
3041 $tags['meta-generator'] = Html
::element( 'meta', array(
3042 'name' => 'generator',
3043 'content' => "MediaWiki $wgVersion",
3046 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3047 if( $p !== 'index,follow' ) {
3048 // http://www.robotstxt.org/wc/meta-user.html
3049 // Only show if it's different from the default robots policy
3050 $tags['meta-robots'] = Html
::element( 'meta', array(
3056 if ( count( $this->mKeywords
) > 0 ) {
3058 "/<.*?" . ">/" => '',
3061 $tags['meta-keywords'] = Html
::element( 'meta', array(
3062 'name' => 'keywords',
3063 'content' => preg_replace(
3064 array_keys( $strip ),
3065 array_values( $strip ),
3066 implode( ',', $this->mKeywords
)
3071 foreach ( $this->mMetatags
as $tag ) {
3072 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3074 $tag[0] = substr( $tag[0], 5 );
3078 $tagName = "meta-{$tag[0]}";
3079 if ( isset( $tags[$tagName] ) ) {
3080 $tagName .= $tag[1];
3082 $tags[$tagName] = Html
::element( 'meta',
3085 'content' => $tag[1]
3090 foreach ( $this->mLinktags
as $tag ) {
3091 $tags[] = Html
::element( 'link', $tag );
3094 # Universal edit button
3095 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3096 $user = $this->getUser();
3097 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3098 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3099 // Original UniversalEditButton
3100 $msg = $this->msg( 'edit' )->text();
3101 $tags['universal-edit-button'] = Html
::element( 'link', array(
3102 'rel' => 'alternate',
3103 'type' => 'application/x-wiki',
3105 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3107 // Alternate edit link
3108 $tags['alternative-edit'] = Html
::element( 'link', array(
3111 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3116 # Generally the order of the favicon and apple-touch-icon links
3117 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3118 # uses whichever one appears later in the HTML source. Make sure
3119 # apple-touch-icon is specified first to avoid this.
3120 if ( $wgAppleTouchIcon !== false ) {
3121 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3124 if ( $wgFavicon !== false ) {
3125 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3128 # OpenSearch description link
3129 $tags['opensearch'] = Html
::element( 'link', array(
3131 'type' => 'application/opensearchdescription+xml',
3132 'href' => wfScript( 'opensearch_desc' ),
3133 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3136 if ( $wgEnableAPI ) {
3137 # Real Simple Discovery link, provides auto-discovery information
3138 # for the MediaWiki API (and potentially additional custom API
3139 # support such as WordPress or Twitter-compatible APIs for a
3140 # blogging extension, etc)
3141 $tags['rsd'] = Html
::element( 'link', array(
3143 'type' => 'application/rsd+xml',
3144 // Output a protocol-relative URL here if $wgServer is protocol-relative
3145 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3146 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3152 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3153 $lang = $this->getTitle()->getPageLanguage();
3154 if ( $lang->hasVariants() ) {
3156 $urlvar = $lang->getURLVariant();
3159 $variants = $lang->getVariants();
3160 foreach ( $variants as $_v ) {
3161 $tags["variant-$_v"] = Html
::element( 'link', array(
3162 'rel' => 'alternate',
3164 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3168 $tags['canonical'] = Html
::element( 'link', array(
3169 'rel' => 'canonical',
3170 'href' => $this->getTitle()->getCanonicalUrl()
3178 if ( $wgRightsPage ) {
3179 $copy = Title
::newFromText( $wgRightsPage );
3182 $copyright = $copy->getLocalURL();
3186 if ( !$copyright && $wgRightsUrl ) {
3187 $copyright = $wgRightsUrl;
3191 $tags['copyright'] = Html
::element( 'link', array(
3192 'rel' => 'copyright',
3193 'href' => $copyright )
3199 foreach( $this->getSyndicationLinks() as $format => $link ) {
3200 # Use the page name for the title. In principle, this could
3201 # lead to issues with having the same name for different feeds
3202 # corresponding to the same page, but we can't avoid that at
3205 $tags[] = $this->feedLink(
3208 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3209 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3213 # Recent changes feed should appear on every page (except recentchanges,
3214 # that would be redundant). Put it after the per-page feed to avoid
3215 # changing existing behavior. It's still available, probably via a
3216 # menu in your browser. Some sites might have a different feed they'd
3217 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3218 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3219 # If so, use it instead.
3220 if ( $wgOverrideSiteFeed ) {
3221 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3222 // Note, this->feedLink escapes the url.
3223 $tags[] = $this->feedLink(
3226 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3229 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3230 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3231 foreach ( $wgAdvertisedFeedTypes as $format ) {
3232 $tags[] = $this->feedLink(
3234 $rctitle->getLocalURL( "feed={$format}" ),
3235 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3245 * @param $addContentType bool: Whether <meta> specifying content type should be returned
3247 * @return string HTML tag links to be put in the header.
3249 public function getHeadLinks( $unused = null, $addContentType = false ) {
3250 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3254 * Generate a <link rel/> for a feed.
3256 * @param $type String: feed type
3257 * @param $url String: URL to the feed
3258 * @param $text String: value of the "title" attribute
3259 * @return String: HTML fragment
3261 private function feedLink( $type, $url, $text ) {
3262 return Html
::element( 'link', array(
3263 'rel' => 'alternate',
3264 'type' => "application/$type+xml",
3271 * Add a local or specified stylesheet, with the given media options.
3272 * Meant primarily for internal use...
3274 * @param $style String: URL to the file
3275 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3276 * @param $condition String: for IE conditional comments, specifying an IE version
3277 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3279 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3281 // Even though we expect the media type to be lowercase, but here we
3282 // force it to lowercase to be safe.
3284 $options['media'] = $media;
3287 $options['condition'] = $condition;
3290 $options['dir'] = $dir;
3292 $this->styles
[$style] = $options;
3296 * Adds inline CSS styles
3297 * @param $style_css Mixed: inline CSS
3298 * @param $flip String: Set to 'flip' to flip the CSS if needed
3300 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3301 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3302 # If wanted, and the interface is right-to-left, flip the CSS
3303 $style_css = CSSJanus
::transform( $style_css, true, false );
3305 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3309 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3310 * These will be applied to various media & IE conditionals.
3314 public function buildCssLinks() {
3315 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3316 $wgLang, $wgContLang;
3318 $this->getSkin()->setupSkinUserCss( $this );
3320 // Add ResourceLoader styles
3321 // Split the styles into four groups
3322 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3323 $otherTags = ''; // Tags to append after the normal <link> tags
3324 $resourceLoader = $this->getResourceLoader();
3326 $moduleStyles = $this->getModuleStyles();
3328 // Per-site custom styles
3329 if ( $wgUseSiteCss ) {
3330 $moduleStyles[] = 'site';
3331 $moduleStyles[] = 'noscript';
3332 if( $this->getUser()->isLoggedIn() ){
3333 $moduleStyles[] = 'user.groups';
3337 // Per-user custom styles
3338 if ( $wgAllowUserCss ) {
3339 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3340 // We're on a preview of a CSS subpage
3341 // Exclude this page from the user module in case it's in there (bug 26283)
3342 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3343 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3346 // Load the previewed CSS
3347 // If needed, Janus it first. This is user-supplied CSS, so it's
3348 // assumed to be right for the content language directionality.
3349 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3350 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3351 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3353 $otherTags .= Html
::inlineStyle( $previewedCSS );
3355 // Load the user styles normally
3356 $moduleStyles[] = 'user';
3360 // Per-user preference styles
3361 if ( $wgAllowUserCssPrefs ) {
3362 $moduleStyles[] = 'user.cssprefs';
3365 foreach ( $moduleStyles as $name ) {
3366 $module = $resourceLoader->getModule( $name );
3370 $group = $module->getGroup();
3371 // Modules in groups named "other" or anything different than "user", "site" or "private"
3372 // will be placed in the "other" group
3373 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3376 // We want site, private and user styles to override dynamically added styles from modules, but we want
3377 // dynamically added styles to override statically added styles from other modules. So the order
3378 // has to be other, dynamic, site, private, user
3379 // Add statically added styles for other modules
3380 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3381 // Add normal styles added through addStyle()/addInlineStyle() here
3382 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3383 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3384 // We use a <meta> tag with a made-up name for this because that's valid HTML
3385 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3387 // Add site, private and user styles
3388 // 'private' at present only contains user.options, so put that before 'user'
3389 // Any future private modules will likely have a similar user-specific character
3390 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3391 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3392 ResourceLoaderModule
::TYPE_STYLES
3396 // Add stuff in $otherTags (previewed user CSS if applicable)
3404 public function buildCssLinksArray() {
3407 // Add any extension CSS
3408 foreach ( $this->mExtStyles
as $url ) {
3409 $this->addStyle( $url );
3411 $this->mExtStyles
= array();
3413 foreach( $this->styles
as $file => $options ) {
3414 $link = $this->styleLink( $file, $options );
3416 $links[$file] = $link;
3423 * Generate \<link\> tags for stylesheets
3425 * @param $style String: URL to the file
3426 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3428 * @return String: HTML fragment
3430 protected function styleLink( $style, $options ) {
3431 if( isset( $options['dir'] ) ) {
3432 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3437 if( isset( $options['media'] ) ) {
3438 $media = self
::transformCssMedia( $options['media'] );
3439 if( is_null( $media ) ) {
3446 if( substr( $style, 0, 1 ) == '/' ||
3447 substr( $style, 0, 5 ) == 'http:' ||
3448 substr( $style, 0, 6 ) == 'https:' ) {
3451 global $wgStylePath, $wgStyleVersion;
3452 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3455 $link = Html
::linkedStyle( $url, $media );
3457 if( isset( $options['condition'] ) ) {
3458 $condition = htmlspecialchars( $options['condition'] );
3459 $link = "<!--[if $condition]>$link<![endif]-->";
3465 * Transform "media" attribute based on request parameters
3467 * @param $media String: current value of the "media" attribute
3468 * @return String: modified value of the "media" attribute
3470 public static function transformCssMedia( $media ) {
3471 global $wgRequest, $wgHandheldForIPhone;
3473 // Switch in on-screen display for media testing
3475 'printable' => 'print',
3476 'handheld' => 'handheld',
3478 foreach( $switches as $switch => $targetMedia ) {
3479 if( $wgRequest->getBool( $switch ) ) {
3480 if( $media == $targetMedia ) {
3482 } elseif( $media == 'screen' ) {
3488 // Expand longer media queries as iPhone doesn't grok 'handheld'
3489 if( $wgHandheldForIPhone ) {
3490 $mediaAliases = array(
3491 'screen' => 'screen and (min-device-width: 481px)',
3492 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3495 if( isset( $mediaAliases[$media] ) ) {
3496 $media = $mediaAliases[$media];
3504 * Add a wikitext-formatted message to the output.
3505 * This is equivalent to:
3507 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3509 public function addWikiMsg( /*...*/ ) {
3510 $args = func_get_args();
3511 $name = array_shift( $args );
3512 $this->addWikiMsgArray( $name, $args );
3516 * Add a wikitext-formatted message to the output.
3517 * Like addWikiMsg() except the parameters are taken as an array
3518 * instead of a variable argument list.
3520 * @param $name string
3521 * @param $args array
3523 public function addWikiMsgArray( $name, $args ) {
3524 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3528 * This function takes a number of message/argument specifications, wraps them in
3529 * some overall structure, and then parses the result and adds it to the output.
3531 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3532 * on. The subsequent arguments may either be strings, in which case they are the
3533 * message names, or arrays, in which case the first element is the message name,
3534 * and subsequent elements are the parameters to that message.
3536 * The special named parameter 'options' in a message specification array is passed
3537 * through to the $options parameter of wfMsgExt().
3539 * Don't use this for messages that are not in users interface language.
3543 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3547 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3549 * The newline after opening div is needed in some wikitext. See bug 19226.
3551 * @param $wrap string
3553 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3554 $msgSpecs = func_get_args();
3555 array_shift( $msgSpecs );
3556 $msgSpecs = array_values( $msgSpecs );
3558 foreach ( $msgSpecs as $n => $spec ) {
3560 if ( is_array( $spec ) ) {
3562 $name = array_shift( $args );
3563 if ( isset( $args['options'] ) ) {
3564 $options = $args['options'];
3565 unset( $args['options'] );
3571 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3573 $this->addWikiText( $s );
3577 * Include jQuery core. Use this to avoid loading it multiple times
3578 * before we get a usable script loader.
3580 * @param $modules Array: list of jQuery modules which should be loaded
3581 * @return Array: the list of modules which were not loaded.
3583 * @deprecated since 1.17
3585 public function includeJQuery( $modules = array() ) {