2 if ( !defined( 'MEDIAWIKI' ) ) {
7 * This class should be covered by a general architecture document which does
8 * not exist as of january 2011. This is one of the Core class and should
9 * be read at least once by any new developers.
11 * This class is used to prepare the final rendering. A skin is then
12 * applied to the output parameters (links, javascript, html, categories ...).
14 * Another class (fixme) handle sending the whole page to the client.
16 * Some comments comes from a pairing session between Zak Greant and Ashar Voultoiz
22 /// Should be private. Used with addMeta() which adds <meta>
23 var $mMetatags = array();
25 /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
26 var $mKeywords = array();
28 var $mLinktags = array();
30 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
31 var $mExtStyles = array();
33 /// Should be private - has getter and setter. Contains the HTML title
36 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
40 * Holds the debug lines that will be outputted as comments in page source if
41 * $wgDebugComments is enabled. See also $wgShowDebug.
42 * TODO: make a getter method for this
44 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
46 /// Should be private. Stores contents of <title> tag
49 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = true;
53 * Should be private. We have to set isPrintable(). Some pages should
54 * never be printed (ex: redirections).
56 var $mPrintable = false;
59 * Should be private. We have set/get/append methods.
61 * Contains the page subtitle. Special pages usually have some links here.
62 * Don't confuse with site subtitle added by skins.
70 * mLastModified and mEtag are used for sending cache control.
71 * The whole caching system should probably be moved in its own class.
73 var $mLastModified = '';
76 * Should be private. No getter but used in sendCacheControl();
77 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
78 * as a unique identifier for the content. It is later used by the client
79 * to compare its cache version with the server version. Client sends
80 * headers If-Match and If-None-Match containing its local cache ETAG value.
82 * To get more information, you will have to look at HTTP1/1 protocols which
83 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
87 var $mCategoryLinks = array();
88 var $mCategories = array();
90 /// Should be private. Associative array mapping language code to the page name
91 var $mLanguageLinks = array();
94 * Should be private. Used for JavaScript (pre resource loader)
95 * We should split js / css.
96 * mScripts content is inserted as is in <head> by Skin. This might contains
97 * either a link to a stylesheet or inline css.
102 * Inline CSS styles. Use addInlineStyle() sparsingly
104 var $mInlineStyles = '';
110 * Used by skin template.
111 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
113 var $mPageLinkTitle = '';
115 /// Array of elements in <head>. Parser might add its own headers!
116 var $mHeadItems = array();
118 // Next variables probably comes from the resource loader @todo FIXME
119 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
120 var $mResourceLoader;
122 /** @fixme is this still used ?*/
123 var $mInlineMsg = array();
125 var $mTemplateIds = array();
127 /** Initialized with a global value. Let us override it.
128 * Should probably get deleted / rewritten ... */
132 * @EasterEgg I just love the name for this self documenting variable.
135 var $mDoNothing = false;
138 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
141 * Should be private. Has get/set methods properly documented.
142 * Stores "article flag" toggle.
144 var $mIsArticleRelated = true;
146 /// lazy initialised, use parserOptions()
147 protected $mParserOptions = null;
150 * Handles the atom / rss links.
151 * We probably only support atom in 2011.
152 * Looks like a private variable.
153 * @see $wgAdvertisedFeedTypes
155 var $mFeedLinks = array();
157 // Gwicke work on squid caching? Roughly from 2003.
158 var $mEnableClientCache = true;
161 * Flag if output should only contain the body of the article.
164 var $mArticleBodyOnly = false;
166 var $mNewSectionLink = false;
167 var $mHideNewSectionLink = false;
170 * Comes from the parser. This was probably made to load CSS/JS only
171 * if we had <gallery>. Used directly in CategoryPage.php
172 * Looks like resource loader can replace this.
174 var $mNoGallery = false;
176 // should be private.
177 var $mPageTitleActionText = '';
178 var $mParseWarnings = array();
180 // Cache stuff. Looks like mEnableClientCache
181 var $mSquidMaxage = 0;
184 var $mPreventClickjacking = true;
186 /// should be private. To include the variable {{REVISIONID}}
187 var $mRevisionId = null;
189 /// Stores a Title object (of the current page).
190 protected $mTitle = null;
193 * An array of stylesheet filenames (relative from skins path), with options
194 * for CSS media, IE conditions, and RTL/LTR direction.
195 * For internal use; add settings in the skin via $this->addStyle()
197 * Style again! This seems like a code duplication since we already have
198 * mStyles. This is what makes OpenSource amazing.
200 var $styles = array();
203 * Whether jQuery is already handled.
205 protected $mJQueryDone = false;
207 private $mIndexPolicy = 'index';
208 private $mFollowPolicy = 'follow';
209 private $mVaryHeader = array(
210 'Accept-Encoding' => array( 'list-contains=gzip' ),
216 * Initialise private variables
218 function __construct() {
219 global $wgAllowUserJs;
220 $this->mAllowUserJs
= $wgAllowUserJs;
224 * Redirect to $url rather than displaying the normal page
226 * @param $url String: URL
227 * @param $responsecode String: HTTP status code
229 public function redirect( $url, $responsecode = '302' ) {
230 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
231 $this->mRedirect
= str_replace( "\n", '', $url );
232 $this->mRedirectCode
= $responsecode;
236 * Get the URL to redirect to, or an empty string if not redirect URL set
240 public function getRedirect() {
241 return $this->mRedirect
;
245 * Set the HTTP status code to send with the output.
247 * @param $statusCode Integer
249 public function setStatusCode( $statusCode ) {
250 $this->mStatusCode
= $statusCode;
254 * Add a new <meta> tag
255 * To add an http-equiv meta tag, precede the name with "http:"
257 * @param $name String tag name
258 * @param $val String tag value
260 function addMeta( $name, $val ) {
261 array_push( $this->mMetatags
, array( $name, $val ) );
265 * Add a keyword or a list of keywords in the page header
267 * @param $text String or array of strings
269 function addKeyword( $text ) {
270 if( is_array( $text ) ) {
271 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
273 array_push( $this->mKeywords
, $text );
278 * Add a new \<link\> tag to the page header
280 * @param $linkarr Array: associative array of attributes.
282 function addLink( $linkarr ) {
283 array_push( $this->mLinktags
, $linkarr );
287 * Add a new \<link\> with "rel" attribute set to "meta"
289 * @param $linkarr Array: associative array mapping attribute names to their
290 * values, both keys and values will be escaped, and the
291 * "rel" attribute will be automatically added
293 function addMetadataLink( $linkarr ) {
294 # note: buggy CC software only reads first "meta" link
295 static $haveMeta = false;
296 $linkarr['rel'] = $haveMeta ?
'alternate meta' : 'meta';
297 $this->addLink( $linkarr );
302 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
304 * @param $script String: raw HTML
306 function addScript( $script ) {
307 $this->mScripts
.= $script . "\n";
311 * Register and add a stylesheet from an extension directory.
313 * @param $url String path to sheet. Provide either a full url (beginning
314 * with 'http', etc) or a relative path from the document root
315 * (beginning with '/'). Otherwise it behaves identically to
316 * addStyle() and draws from the /skins folder.
318 public function addExtensionStyle( $url ) {
319 array_push( $this->mExtStyles
, $url );
323 * Get all styles added by extensions
327 function getExtStyle() {
328 return $this->mExtStyles
;
332 * Add a JavaScript file out of skins/common, or a given relative path.
334 * @param $file String: filename in skins/common or complete on-server path
336 * @param $version String: style version of the file. Defaults to $wgStyleVersion
338 public function addScriptFile( $file, $version = null ) {
339 global $wgStylePath, $wgStyleVersion;
340 // See if $file parameter is an absolute URL or begins with a slash
341 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
344 $path = "{$wgStylePath}/common/{$file}";
346 if ( is_null( $version ) )
347 $version = $wgStyleVersion;
348 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
352 * Add a self-contained script tag with the given contents
354 * @param $script String: JavaScript text, no <script> tags
356 public function addInlineScript( $script ) {
357 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
361 * Get all registered JS and CSS tags for the header.
365 function getScript() {
366 return $this->mScripts
. $this->getHeadItems();
370 * Get the list of modules to include on this page
372 * @return Array of module names
374 public function getModules() {
375 return array_values( array_unique( $this->mModules
) );
379 * Add one or more modules recognized by the resource loader. Modules added
380 * through this function will be loaded by the resource loader when the
383 * @param $modules Mixed: module name (string) or array of module names
385 public function addModules( $modules ) {
386 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
390 * Get the list of module JS to include on this page
391 * @return array of module names
393 public function getModuleScripts() {
394 return array_values( array_unique( $this->mModuleScripts
) );
398 * Add only JS of one or more modules recognized by the resource loader. Module
399 * scripts added through this function will be loaded by the resource loader when
402 * @param $modules Mixed: module name (string) or array of module names
404 public function addModuleScripts( $modules ) {
405 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
409 * Get the list of module CSS to include on this page
411 * @return Array of module names
413 public function getModuleStyles() {
414 return array_values( array_unique( $this->mModuleStyles
) );
418 * Add only CSS of one or more modules recognized by the resource loader. Module
419 * styles added through this function will be loaded by the resource loader when
422 * @param $modules Mixed: module name (string) or array of module names
424 public function addModuleStyles( $modules ) {
425 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
429 * Get the list of module messages to include on this page
431 * @return Array of module names
433 public function getModuleMessages() {
434 return array_values( array_unique( $this->mModuleMessages
) );
438 * Add only messages of one or more modules recognized by the resource loader.
439 * Module messages added through this function will be loaded by the resource
440 * loader when the page loads.
442 * @param $modules Mixed: module name (string) or array of module names
444 public function addModuleMessages( $modules ) {
445 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
449 * Get all header items in a string
453 function getHeadItems() {
455 foreach ( $this->mHeadItems
as $item ) {
462 * Add or replace an header item to the output
464 * @param $name String: item name
465 * @param $value String: raw HTML
467 public function addHeadItem( $name, $value ) {
468 $this->mHeadItems
[$name] = $value;
472 * Check if the header item $name is already set
474 * @param $name String: item name
477 public function hasHeadItem( $name ) {
478 return isset( $this->mHeadItems
[$name] );
482 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
484 * @param $tag String: value of "ETag" header
486 function setETag( $tag ) {
491 * Set whether the output should only contain the body of the article,
492 * without any skin, sidebar, etc.
493 * Used e.g. when calling with "action=render".
495 * @param $only Boolean: whether to output only the body of the article
497 public function setArticleBodyOnly( $only ) {
498 $this->mArticleBodyOnly
= $only;
502 * Return whether the output will contain only the body of the article
506 public function getArticleBodyOnly() {
507 return $this->mArticleBodyOnly
;
511 * checkLastModified tells the client to use the client-cached page if
512 * possible. If sucessful, the OutputPage is disabled so that
513 * any future call to OutputPage->output() have no effect.
515 * Side effect: sets mLastModified for Last-Modified header
517 * @return Boolean: true iff cache-ok headers was sent.
519 public function checkLastModified( $timestamp ) {
520 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
522 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
523 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
526 if( !$wgCachePages ) {
527 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
530 if( $wgUser->getOption( 'nocache' ) ) {
531 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
535 $timestamp = wfTimestamp( TS_MW
, $timestamp );
536 $modifiedTimes = array(
537 'page' => $timestamp,
538 'user' => $wgUser->getTouched(),
539 'epoch' => $wgCacheEpoch
541 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
543 $maxModified = max( $modifiedTimes );
544 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
546 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
547 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
553 foreach ( $modifiedTimes as $name => $value ) {
554 if ( $info !== '' ) {
557 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
560 # IE sends sizes after the date like this:
561 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
562 # this breaks strtotime().
563 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
565 wfSuppressWarnings(); // E_STRICT system time bitching
566 $clientHeaderTime = strtotime( $clientHeader );
568 if ( !$clientHeaderTime ) {
569 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
572 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
574 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
575 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
576 wfDebug( __METHOD__
. ": effective Last-Modified: " .
577 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
578 if( $clientHeaderTime < $maxModified ) {
579 wfDebug( __METHOD__
. ": STALE, $info\n", false );
584 # Give a 304 response code and disable body output
585 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
586 ini_set( 'zlib.output_compression', 0 );
587 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
588 $this->sendCacheControl();
591 // Don't output a compressed blob when using ob_gzhandler;
592 // it's technically against HTTP spec and seems to confuse
593 // Firefox when the response gets split over two packets.
594 wfClearOutputBuffers();
600 * Override the last modified timestamp
602 * @param $timestamp String: new timestamp, in a format readable by
605 public function setLastModified( $timestamp ) {
606 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
610 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
612 * @param $policy String: the literal string to output as the contents of
613 * the meta tag. Will be parsed according to the spec and output in
617 public function setRobotPolicy( $policy ) {
618 $policy = Article
::formatRobotPolicy( $policy );
620 if( isset( $policy['index'] ) ) {
621 $this->setIndexPolicy( $policy['index'] );
623 if( isset( $policy['follow'] ) ) {
624 $this->setFollowPolicy( $policy['follow'] );
629 * Set the index policy for the page, but leave the follow policy un-
632 * @param $policy string Either 'index' or 'noindex'.
635 public function setIndexPolicy( $policy ) {
636 $policy = trim( $policy );
637 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
638 $this->mIndexPolicy
= $policy;
643 * Set the follow policy for the page, but leave the index policy un-
646 * @param $policy String: either 'follow' or 'nofollow'.
649 public function setFollowPolicy( $policy ) {
650 $policy = trim( $policy );
651 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
652 $this->mFollowPolicy
= $policy;
657 * Set the new value of the "action text", this will be added to the
658 * "HTML title", separated from it with " - ".
660 * @param $text String: new value of the "action text"
662 public function setPageTitleActionText( $text ) {
663 $this->mPageTitleActionText
= $text;
667 * Get the value of the "action text"
671 public function getPageTitleActionText() {
672 if ( isset( $this->mPageTitleActionText
) ) {
673 return $this->mPageTitleActionText
;
678 * "HTML title" means the contents of <title>.
679 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
681 public function setHTMLTitle( $name ) {
682 $this->mHTMLtitle
= $name;
686 * Return the "HTML title", i.e. the content of the <title> tag.
690 public function getHTMLTitle() {
691 return $this->mHTMLtitle
;
695 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
696 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
697 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
698 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
700 public function setPageTitle( $name ) {
701 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
702 # but leave "<i>foobar</i>" alone
703 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
704 $this->mPagetitle
= $nameWithTags;
706 # change "<i>foo&bar</i>" to "foo&bar"
707 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
711 * Return the "page title", i.e. the content of the \<h1\> tag.
715 public function getPageTitle() {
716 return $this->mPagetitle
;
720 * Set the Title object to use
722 * @param $t Title object
724 public function setTitle( $t ) {
729 * Get the Title object used in this instance
733 public function getTitle() {
734 if ( $this->mTitle
instanceof Title
) {
735 return $this->mTitle
;
737 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
744 * Replace the subtile with $str
746 * @param $str String: new value of the subtitle
748 public function setSubtitle( $str ) {
749 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
753 * Add $str to the subtitle
755 * @param $str String to add to the subtitle
757 public function appendSubtitle( $str ) {
758 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
766 public function getSubtitle() {
767 return $this->mSubtitle
;
771 * Set the page as printable, i.e. it'll be displayed with with all
772 * print styles included
774 public function setPrintable() {
775 $this->mPrintable
= true;
779 * Return whether the page is "printable"
783 public function isPrintable() {
784 return $this->mPrintable
;
788 * Disable output completely, i.e. calling output() will have no effect
790 public function disable() {
791 $this->mDoNothing
= true;
795 * Return whether the output will be completely disabled
799 public function isDisabled() {
800 return $this->mDoNothing
;
804 * Show an "add new section" link?
808 public function showNewSectionLink() {
809 return $this->mNewSectionLink
;
813 * Forcibly hide the new section link?
817 public function forceHideNewSectionLink() {
818 return $this->mHideNewSectionLink
;
822 * Add or remove feed links in the page header
823 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
824 * for the new version
827 * @param $show Boolean: true: add default feeds, false: remove all feeds
829 public function setSyndicated( $show = true ) {
831 $this->setFeedAppendQuery( false );
833 $this->mFeedLinks
= array();
838 * Add default feeds to the page header
839 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
840 * for the new version
843 * @param $val String: query to append to feed links or false to output
846 public function setFeedAppendQuery( $val ) {
847 global $wgAdvertisedFeedTypes;
849 $this->mFeedLinks
= array();
851 foreach ( $wgAdvertisedFeedTypes as $type ) {
852 $query = "feed=$type";
853 if ( is_string( $val ) ) {
854 $query .= '&' . $val;
856 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
861 * Add a feed link to the page header
863 * @param $format String: feed type, should be a key of $wgFeedClasses
864 * @param $href String: URL
866 public function addFeedLink( $format, $href ) {
867 global $wgAdvertisedFeedTypes;
869 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
870 $this->mFeedLinks
[$format] = $href;
875 * Should we output feed links for this page?
878 public function isSyndicated() {
879 return count( $this->mFeedLinks
) > 0;
883 * Return URLs for each supported syndication format for this page.
884 * @return array associating format keys with URLs
886 public function getSyndicationLinks() {
887 return $this->mFeedLinks
;
891 * Will currently always return null
895 public function getFeedAppendQuery() {
896 return $this->mFeedLinksAppendQuery
;
900 * Set whether the displayed content is related to the source of the
901 * corresponding article on the wiki
902 * Setting true will cause the change "article related" toggle to true
906 public function setArticleFlag( $v ) {
907 $this->mIsarticle
= $v;
909 $this->mIsArticleRelated
= $v;
914 * Return whether the content displayed page is related to the source of
915 * the corresponding article on the wiki
919 public function isArticle() {
920 return $this->mIsarticle
;
924 * Set whether this page is related an article on the wiki
925 * Setting false will cause the change of "article flag" toggle to false
929 public function setArticleRelated( $v ) {
930 $this->mIsArticleRelated
= $v;
932 $this->mIsarticle
= false;
937 * Return whether this page is related an article on the wiki
941 public function isArticleRelated() {
942 return $this->mIsArticleRelated
;
946 * Add new language links
948 * @param $newLinkArray Associative array mapping language code to the page
951 public function addLanguageLinks( $newLinkArray ) {
952 $this->mLanguageLinks +
= $newLinkArray;
956 * Reset the language links and add new language links
958 * @param $newLinkArray Associative array mapping language code to the page
961 public function setLanguageLinks( $newLinkArray ) {
962 $this->mLanguageLinks
= $newLinkArray;
966 * Get the list of language links
968 * @return Associative array mapping language code to the page name
970 public function getLanguageLinks() {
971 return $this->mLanguageLinks
;
975 * Add an array of categories, with names in the keys
977 * @param $categories Array mapping category name => sort key
979 public function addCategoryLinks( $categories ) {
980 global $wgUser, $wgContLang;
982 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
986 # Add the links to a LinkBatch
987 $arr = array( NS_CATEGORY
=> $categories );
989 $lb->setArray( $arr );
991 # Fetch existence plus the hiddencat property
992 $dbr = wfGetDB( DB_SLAVE
);
993 $res = $dbr->select( array( 'page', 'page_props' ),
994 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
995 $lb->constructSet( 'page', $dbr ),
998 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1001 # Add the results to the link cache
1002 $lb->addResultToCache( LinkCache
::singleton(), $res );
1004 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1005 $categories = array_combine(
1006 array_keys( $categories ),
1007 array_fill( 0, count( $categories ), 'normal' )
1010 # Mark hidden categories
1011 foreach ( $res as $row ) {
1012 if ( isset( $row->pp_value
) ) {
1013 $categories[$row->page_title
] = 'hidden';
1017 # Add the remaining categories to the skin
1018 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1019 $sk = $wgUser->getSkin();
1020 foreach ( $categories as $category => $type ) {
1021 $origcategory = $category;
1022 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1023 $wgContLang->findVariantLink( $category, $title, true );
1024 if ( $category != $origcategory ) {
1025 if ( array_key_exists( $category, $categories ) ) {
1029 $text = $wgContLang->convertHtml( $title->getText() );
1030 $this->mCategories
[] = $title->getText();
1031 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
1037 * Reset the category links (but not the category list) and add $categories
1039 * @param $categories Array mapping category name => sort key
1041 public function setCategoryLinks( $categories ) {
1042 $this->mCategoryLinks
= array();
1043 $this->addCategoryLinks( $categories );
1047 * Get the list of category links, in a 2-D array with the following format:
1048 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1049 * hidden categories) and $link a HTML fragment with a link to the category
1054 public function getCategoryLinks() {
1055 return $this->mCategoryLinks
;
1059 * Get the list of category names this page belongs to
1061 * @return Array of strings
1063 public function getCategories() {
1064 return $this->mCategories
;
1068 * Remove user JavaScript from scripts to load
1070 public function disallowUserJs() {
1071 $this->mAllowUserJs
= false;
1075 * Return whether user JavaScript is allowed for this page
1079 public function isUserJsAllowed() {
1080 return $this->mAllowUserJs
;
1084 * Prepend $text to the body HTML
1086 * @param $text String: HTML
1088 public function prependHTML( $text ) {
1089 $this->mBodytext
= $text . $this->mBodytext
;
1093 * Append $text to the body HTML
1095 * @param $text String: HTML
1097 public function addHTML( $text ) {
1098 $this->mBodytext
.= $text;
1102 * Clear the body HTML
1104 public function clearHTML() {
1105 $this->mBodytext
= '';
1111 * @return String: HTML
1113 public function getHTML() {
1114 return $this->mBodytext
;
1118 * Add $text to the debug output
1120 * @param $text String: debug text
1122 public function debug( $text ) {
1123 $this->mDebugtext
.= $text;
1127 * Get/set the ParserOptions object to use for wikitext parsing
1129 * @param $options either the ParserOption to use or null to only get the
1130 * current ParserOption object
1131 * @return current ParserOption object
1133 public function parserOptions( $options = null ) {
1134 if ( !$this->mParserOptions
) {
1135 $this->mParserOptions
= new ParserOptions
;
1137 return wfSetVar( $this->mParserOptions
, $options );
1141 * Set the revision ID which will be seen by the wiki text parser
1142 * for things such as embedded {{REVISIONID}} variable use.
1144 * @param $revid Mixed: an positive integer, or null
1145 * @return Mixed: previous value
1147 public function setRevisionId( $revid ) {
1148 $val = is_null( $revid ) ?
null : intval( $revid );
1149 return wfSetVar( $this->mRevisionId
, $val );
1153 * Get the current revision ID
1157 public function getRevisionId() {
1158 return $this->mRevisionId
;
1162 * Convert wikitext to HTML and add it to the buffer
1163 * Default assumes that the current page title will be used.
1165 * @param $text String
1166 * @param $linestart Boolean: is this the start of a line?
1168 public function addWikiText( $text, $linestart = true ) {
1169 $title = $this->getTitle(); // Work arround E_STRICT
1170 $this->addWikiTextTitle( $text, $title, $linestart );
1174 * Add wikitext with a custom Title object
1176 * @param $text String: wikitext
1177 * @param $title Title object
1178 * @param $linestart Boolean: is this the start of a line?
1180 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1181 $this->addWikiTextTitle( $text, $title, $linestart );
1185 * Add wikitext with a custom Title object and
1187 * @param $text String: wikitext
1188 * @param $title Title object
1189 * @param $linestart Boolean: is this the start of a line?
1191 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1192 $this->addWikiTextTitle( $text, $title, $linestart, true );
1196 * Add wikitext with tidy enabled
1198 * @param $text String: wikitext
1199 * @param $linestart Boolean: is this the start of a line?
1201 public function addWikiTextTidy( $text, $linestart = true ) {
1202 $title = $this->getTitle();
1203 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1207 * Add wikitext with a custom Title object
1209 * @param $text String: wikitext
1210 * @param $title Title object
1211 * @param $linestart Boolean: is this the start of a line?
1212 * @param $tidy Boolean: whether to use tidy
1214 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1217 wfProfileIn( __METHOD__
);
1219 wfIncrStats( 'pcache_not_possible' );
1221 $popts = $this->parserOptions();
1222 $oldTidy = $popts->setTidy( $tidy );
1224 $parserOutput = $wgParser->parse(
1225 $text, $title, $popts,
1226 $linestart, true, $this->mRevisionId
1229 $popts->setTidy( $oldTidy );
1231 $this->addParserOutput( $parserOutput );
1233 wfProfileOut( __METHOD__
);
1237 * Add a ParserOutput object, but without Html
1239 * @param $parserOutput ParserOutput object
1241 public function addParserOutputNoText( &$parserOutput ) {
1242 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1243 $this->addCategoryLinks( $parserOutput->getCategories() );
1244 $this->mNewSectionLink
= $parserOutput->getNewSection();
1245 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1247 $this->mParseWarnings
= $parserOutput->getWarnings();
1248 if ( !$parserOutput->isCacheable() ) {
1249 $this->enableClientCache( false );
1251 $this->mNoGallery
= $parserOutput->getNoGallery();
1252 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1253 $this->addModules( $parserOutput->getModules() );
1255 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1256 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1257 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1259 $this->mTemplateIds
[$ns] = $dbks;
1263 // Hooks registered in the object
1264 global $wgParserOutputHooks;
1265 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1266 list( $hookName, $data ) = $hookInfo;
1267 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1268 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1272 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1276 * Add a ParserOutput object
1278 * @param $parserOutput ParserOutput
1280 function addParserOutput( &$parserOutput ) {
1281 $this->addParserOutputNoText( $parserOutput );
1282 $text = $parserOutput->getText();
1283 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1284 $this->addHTML( $text );
1289 * Add the output of a QuickTemplate to the output buffer
1291 * @param $template QuickTemplate
1293 public function addTemplate( &$template ) {
1295 $template->execute();
1296 $this->addHTML( ob_get_contents() );
1301 * Parse wikitext and return the HTML.
1303 * @param $text String
1304 * @param $linestart Boolean: is this the start of a line?
1305 * @param $interface Boolean: use interface language ($wgLang instead of
1306 * $wgContLang) while parsing language sensitive magic
1307 * words like GRAMMAR and PLURAL
1308 * @param $language Language object: target language object, will override
1310 * @return String: HTML
1312 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1313 // Check one for one common cause for parser state resetting
1314 $callers = wfGetAllCallers( 10 );
1315 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1316 throw new MWException( "wfMsg* function with parsing cannot be used " .
1317 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1322 if( is_null( $this->getTitle() ) ) {
1323 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1326 $popts = $this->parserOptions();
1328 $popts->setInterfaceMessage( true );
1330 if ( $language !== null ) {
1331 $oldLang = $popts->setTargetLanguage( $language );
1334 $parserOutput = $wgParser->parse(
1335 $text, $this->getTitle(), $popts,
1336 $linestart, true, $this->mRevisionId
1340 $popts->setInterfaceMessage( false );
1342 if ( $language !== null ) {
1343 $popts->setTargetLanguage( $oldLang );
1346 return $parserOutput->getText();
1350 * Parse wikitext, strip paragraphs, and return the HTML.
1352 * @param $text String
1353 * @param $linestart Boolean: is this the start of a line?
1354 * @param $interface Boolean: use interface language ($wgLang instead of
1355 * $wgContLang) while parsing language sensitive magic
1356 * words like GRAMMAR and PLURAL
1357 * @return String: HTML
1359 public function parseInline( $text, $linestart = true, $interface = false ) {
1360 $parsed = $this->parse( $text, $linestart, $interface );
1363 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1371 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1373 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1375 public function setSquidMaxage( $maxage ) {
1376 $this->mSquidMaxage
= $maxage;
1380 * Use enableClientCache(false) to force it to send nocache headers
1384 public function enableClientCache( $state ) {
1385 return wfSetVar( $this->mEnableClientCache
, $state );
1389 * Get the list of cookies that will influence on the cache
1393 function getCacheVaryCookies() {
1394 global $wgCookiePrefix, $wgCacheVaryCookies;
1396 if ( $cookies === null ) {
1397 $cookies = array_merge(
1399 "{$wgCookiePrefix}Token",
1400 "{$wgCookiePrefix}LoggedOut",
1405 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1411 * Return whether this page is not cacheable because "useskin" or "uselang"
1412 * URL parameters were passed.
1416 function uncacheableBecauseRequestVars() {
1418 return $wgRequest->getText( 'useskin', false ) === false
1419 && $wgRequest->getText( 'uselang', false ) === false;
1423 * Check if the request has a cache-varying cookie header
1424 * If it does, it's very important that we don't allow public caching
1428 function haveCacheVaryCookies() {
1430 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1431 if ( $cookieHeader === false ) {
1434 $cvCookies = $this->getCacheVaryCookies();
1435 foreach ( $cvCookies as $cookieName ) {
1436 # Check for a simple string match, like the way squid does it
1437 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1438 wfDebug( __METHOD__
. ": found $cookieName\n" );
1442 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1447 * Add an HTTP header that will influence on the cache
1449 * @param $header String: header name
1450 * @param $option Array|null
1451 * @fixme Document the $option parameter; it appears to be for
1452 * X-Vary-Options but what format is acceptable?
1454 public function addVaryHeader( $header, $option = null ) {
1455 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1456 $this->mVaryHeader
[$header] = (array)$option;
1457 } elseif( is_array( $option ) ) {
1458 if( is_array( $this->mVaryHeader
[$header] ) ) {
1459 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1461 $this->mVaryHeader
[$header] = $option;
1464 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1468 * Get a complete X-Vary-Options header
1472 public function getXVO() {
1473 $cvCookies = $this->getCacheVaryCookies();
1475 $cookiesOption = array();
1476 foreach ( $cvCookies as $cookieName ) {
1477 $cookiesOption[] = 'string-contains=' . $cookieName;
1479 $this->addVaryHeader( 'Cookie', $cookiesOption );
1482 foreach( $this->mVaryHeader
as $header => $option ) {
1483 $newheader = $header;
1484 if( is_array( $option ) ) {
1485 $newheader .= ';' . implode( ';', $option );
1487 $headers[] = $newheader;
1489 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1495 * bug 21672: Add Accept-Language to Vary and XVO headers
1496 * if there's no 'variant' parameter existed in GET.
1499 * /w/index.php?title=Main_page should always be served; but
1500 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1502 function addAcceptLanguage() {
1503 global $wgRequest, $wgContLang;
1504 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1505 $variants = $wgContLang->getVariants();
1506 $aloption = array();
1507 foreach ( $variants as $variant ) {
1508 if( $variant === $wgContLang->getCode() ) {
1511 $aloption[] = 'string-contains=' . $variant;
1513 // IE and some other browsers use another form of language code
1514 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1515 // We should handle these too.
1516 $ievariant = explode( '-', $variant );
1517 if ( count( $ievariant ) == 2 ) {
1518 $ievariant[1] = strtoupper( $ievariant[1] );
1519 $ievariant = implode( '-', $ievariant );
1520 $aloption[] = 'string-contains=' . $ievariant;
1524 $this->addVaryHeader( 'Accept-Language', $aloption );
1529 * Set a flag which will cause an X-Frame-Options header appropriate for
1530 * edit pages to be sent. The header value is controlled by
1531 * $wgEditPageFrameOptions.
1533 * This is the default for special pages. If you display a CSRF-protected
1534 * form on an ordinary view page, then you need to call this function.
1536 public function preventClickjacking( $enable = true ) {
1537 $this->mPreventClickjacking
= $enable;
1541 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1542 * This can be called from pages which do not contain any CSRF-protected
1545 public function allowClickjacking() {
1546 $this->mPreventClickjacking
= false;
1550 * Get the X-Frame-Options header value (without the name part), or false
1551 * if there isn't one. This is used by Skin to determine whether to enable
1552 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1554 public function getFrameOptions() {
1555 global $wgBreakFrames, $wgEditPageFrameOptions;
1556 if ( $wgBreakFrames ) {
1558 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1559 return $wgEditPageFrameOptions;
1564 * Send cache control HTTP headers
1566 public function sendCacheControl() {
1567 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1569 $response = $wgRequest->response();
1570 if ( $wgUseETag && $this->mETag
) {
1571 $response->header( "ETag: $this->mETag" );
1574 $this->addAcceptLanguage();
1576 # don't serve compressed data to clients who can't handle it
1577 # maintain different caches for logged-in users and non-logged in ones
1578 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1581 # Add an X-Vary-Options header for Squid with Wikimedia patches
1582 $response->header( $this->getXVO() );
1585 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1587 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1588 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1592 # We'll purge the proxy cache explicitly, but require end user agents
1593 # to revalidate against the proxy on each visit.
1594 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1595 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1596 # start with a shorter timeout for initial testing
1597 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1598 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1599 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1601 # We'll purge the proxy cache for anons explicitly, but require end user agents
1602 # to revalidate against the proxy on each visit.
1603 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1604 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1605 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1606 # start with a shorter timeout for initial testing
1607 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1608 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1611 # We do want clients to cache if they can, but they *must* check for updates
1612 # on revisiting the page.
1613 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1614 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1615 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1617 if($this->mLastModified
) {
1618 $response->header( "Last-Modified: {$this->mLastModified}" );
1621 wfDebug( __METHOD__
. ": no caching **\n", false );
1623 # In general, the absence of a last modified header should be enough to prevent
1624 # the client from using its cache. We send a few other things just to make sure.
1625 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1626 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1627 $response->header( 'Pragma: no-cache' );
1632 * Get the message associed with the HTTP response code $code
1634 * @param $code Integer: status code
1635 * @return String or null: message or null if $code is not in the list of
1638 public static function getStatusMessage( $code ) {
1639 static $statusMessage = array(
1641 101 => 'Switching Protocols',
1642 102 => 'Processing',
1646 203 => 'Non-Authoritative Information',
1647 204 => 'No Content',
1648 205 => 'Reset Content',
1649 206 => 'Partial Content',
1650 207 => 'Multi-Status',
1651 300 => 'Multiple Choices',
1652 301 => 'Moved Permanently',
1655 304 => 'Not Modified',
1657 307 => 'Temporary Redirect',
1658 400 => 'Bad Request',
1659 401 => 'Unauthorized',
1660 402 => 'Payment Required',
1663 405 => 'Method Not Allowed',
1664 406 => 'Not Acceptable',
1665 407 => 'Proxy Authentication Required',
1666 408 => 'Request Timeout',
1669 411 => 'Length Required',
1670 412 => 'Precondition Failed',
1671 413 => 'Request Entity Too Large',
1672 414 => 'Request-URI Too Large',
1673 415 => 'Unsupported Media Type',
1674 416 => 'Request Range Not Satisfiable',
1675 417 => 'Expectation Failed',
1676 422 => 'Unprocessable Entity',
1678 424 => 'Failed Dependency',
1679 500 => 'Internal Server Error',
1680 501 => 'Not Implemented',
1681 502 => 'Bad Gateway',
1682 503 => 'Service Unavailable',
1683 504 => 'Gateway Timeout',
1684 505 => 'HTTP Version Not Supported',
1685 507 => 'Insufficient Storage'
1687 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1691 * Finally, all the text has been munged and accumulated into
1692 * the object, let's actually output it:
1694 public function output() {
1695 global $wgUser, $wgOutputEncoding, $wgRequest;
1696 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1697 global $wgUseAjax, $wgAjaxWatch;
1698 global $wgEnableMWSuggest, $wgUniversalEditButton;
1700 if( $this->mDoNothing
) {
1703 wfProfileIn( __METHOD__
);
1704 if ( $this->mRedirect
!= '' ) {
1705 # Standards require redirect URLs to be absolute
1706 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1707 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1708 if( !$wgDebugRedirects ) {
1709 $message = self
::getStatusMessage( $this->mRedirectCode
);
1710 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1712 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1714 $this->sendCacheControl();
1716 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1717 if( $wgDebugRedirects ) {
1718 $url = htmlspecialchars( $this->mRedirect
);
1719 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1720 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1721 print "</body>\n</html>\n";
1723 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1725 wfProfileOut( __METHOD__
);
1727 } elseif ( $this->mStatusCode
) {
1728 $message = self
::getStatusMessage( $this->mStatusCode
);
1730 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1734 $sk = $wgUser->getSkin();
1736 // Add base resources
1737 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1739 // Add various resources if required
1741 $this->addModules( 'mediawiki.legacy.ajax' );
1743 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1745 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1746 $this->addModules( 'mediawiki.action.watch.ajax' );
1749 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1750 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1754 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1755 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1758 if( $wgUniversalEditButton ) {
1759 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1760 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1761 // Original UniversalEditButton
1762 $msg = wfMsg( 'edit' );
1763 $this->addLink( array(
1764 'rel' => 'alternate',
1765 'type' => 'application/x-wiki',
1767 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1769 // Alternate edit link
1770 $this->addLink( array(
1773 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1779 # Buffer output; final headers may depend on later processing
1782 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1783 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1785 // Prevent framing, if requested
1786 $frameOptions = $this->getFrameOptions();
1787 if ( $frameOptions ) {
1788 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1791 if ( $this->mArticleBodyOnly
) {
1792 $this->out( $this->mBodytext
);
1794 // Hook that allows last minute changes to the output page, e.g.
1795 // adding of CSS or Javascript by extensions.
1796 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1798 wfProfileIn( 'Output-skin' );
1799 $sk->outputPage( $this );
1800 wfProfileOut( 'Output-skin' );
1803 $this->sendCacheControl();
1805 wfProfileOut( __METHOD__
);
1809 * Actually output something with print(). Performs an iconv to the
1810 * output encoding, if needed.
1812 * @param $ins String: the string to output
1814 public function out( $ins ) {
1815 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1816 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1819 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1820 if ( false === $outs ) {
1828 * Produce a "user is blocked" page.
1830 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1833 function blockedPage( $return = true ) {
1834 global $wgUser, $wgContLang, $wgLang;
1836 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1837 $this->setRobotPolicy( 'noindex,nofollow' );
1838 $this->setArticleRelated( false );
1840 $name = User
::whoIs( $wgUser->blockedBy() );
1841 $reason = $wgUser->blockedFor();
1842 if( $reason == '' ) {
1843 $reason = wfMsg( 'blockednoreason' );
1845 $blockTimestamp = $wgLang->timeanddate(
1846 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1850 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1852 $blockid = $wgUser->mBlock
->mId
;
1854 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1855 if ( $blockExpiry == 'infinity' ) {
1856 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1857 // Search for localization in 'ipboptions'
1858 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1859 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1860 if ( strpos( $option, ':' ) === false ) {
1863 list( $show, $value ) = explode( ':', $option );
1864 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1865 $blockExpiry = $show;
1870 $blockExpiry = $wgLang->timeanddate(
1871 wfTimestamp( TS_MW
, $blockExpiry ),
1876 if ( $wgUser->mBlock
->mAuto
) {
1877 $msg = 'autoblockedtext';
1879 $msg = 'blockedtext';
1882 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1883 * This could be a username, an IP range, or a single IP. */
1884 $intended = $wgUser->mBlock
->mAddress
;
1887 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1888 $intended, $blockTimestamp
1891 # Don't auto-return to special pages
1893 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1894 $this->returnToMain( null, $return );
1899 * Output a standard error page
1901 * @param $title String: message key for page title
1902 * @param $msg String: message key for page text
1903 * @param $params Array: message parameters
1905 public function showErrorPage( $title, $msg, $params = array() ) {
1906 if ( $this->getTitle() ) {
1907 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1909 $this->setPageTitle( wfMsg( $title ) );
1910 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1911 $this->setRobotPolicy( 'noindex,nofollow' );
1912 $this->setArticleRelated( false );
1913 $this->enableClientCache( false );
1914 $this->mRedirect
= '';
1915 $this->mBodytext
= '';
1917 $this->addWikiMsgArray( $msg, $params );
1919 $this->returnToMain();
1923 * Output a standard permission error page
1925 * @param $errors Array: error message keys
1926 * @param $action String: action that was denied or null if unknown
1928 public function showPermissionsErrorPage( $errors, $action = null ) {
1929 $this->mDebugtext
.= 'Original title: ' .
1930 $this->getTitle()->getPrefixedText() . "\n";
1931 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1932 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1933 $this->setRobotPolicy( 'noindex,nofollow' );
1934 $this->setArticleRelated( false );
1935 $this->enableClientCache( false );
1936 $this->mRedirect
= '';
1937 $this->mBodytext
= '';
1938 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1942 * Display an error page indicating that a given version of MediaWiki is
1943 * required to use it
1945 * @param $version Mixed: the version of MediaWiki needed to use the page
1947 public function versionRequired( $version ) {
1948 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1949 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1950 $this->setRobotPolicy( 'noindex,nofollow' );
1951 $this->setArticleRelated( false );
1952 $this->mBodytext
= '';
1954 $this->addWikiMsg( 'versionrequiredtext', $version );
1955 $this->returnToMain();
1959 * Display an error page noting that a given permission bit is required.
1961 * @param $permission String: key required
1963 public function permissionRequired( $permission ) {
1966 $this->setPageTitle( wfMsg( 'badaccess' ) );
1967 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1968 $this->setRobotPolicy( 'noindex,nofollow' );
1969 $this->setArticleRelated( false );
1970 $this->mBodytext
= '';
1972 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1973 User
::getGroupsWithPermission( $permission ) );
1977 $wgLang->commaList( $groups ),
1981 $this->addWikiMsg( 'badaccess-group0' );
1983 $this->returnToMain();
1987 * Produce the stock "please login to use the wiki" page
1989 public function loginToUse() {
1992 if( $wgUser->isLoggedIn() ) {
1993 $this->permissionRequired( 'read' );
1997 $skin = $wgUser->getSkin();
1999 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2000 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2001 $this->setRobotPolicy( 'noindex,nofollow' );
2002 $this->setArticleRelated( false );
2004 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2005 $loginLink = $skin->link(
2007 wfMsgHtml( 'loginreqlink' ),
2009 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2010 array( 'known', 'noclasses' )
2012 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
2013 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2015 # Don't return to the main page if the user can't read it
2016 # otherwise we'll end up in a pointless loop
2017 $mainPage = Title
::newMainPage();
2018 if( $mainPage->userCanRead() ) {
2019 $this->returnToMain( null, $mainPage );
2024 * Format a list of error messages
2026 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2027 * @param $action String: action that was denied or null if unknown
2028 * @return String: the wikitext error-messages, formatted into a list.
2030 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2031 if ( $action == null ) {
2032 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2034 $action_desc = wfMsgNoTrans( "action-$action" );
2035 $text = wfMsgNoTrans(
2036 'permissionserrorstext-withaction',
2042 if ( count( $errors ) > 1 ) {
2043 $text .= '<ul class="permissions-errors">' . "\n";
2045 foreach( $errors as $error ) {
2047 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2052 $text .= "<div class=\"permissions-errors\">\n" .
2053 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2061 * Display a page stating that the Wiki is in read-only mode,
2062 * and optionally show the source of the page that the user
2063 * was trying to edit. Should only be called (for this
2064 * purpose) after wfReadOnly() has returned true.
2066 * For historical reasons, this function is _also_ used to
2067 * show the error message when a user tries to edit a page
2068 * they are not allowed to edit. (Unless it's because they're
2069 * blocked, then we show blockedPage() instead.) In this
2070 * case, the second parameter should be set to true and a list
2071 * of reasons supplied as the third parameter.
2073 * @todo Needs to be split into multiple functions.
2075 * @param $source String: source code to show (or null).
2076 * @param $protected Boolean: is this a permissions error?
2077 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2078 * @param $action String: action that was denied or null if unknown
2080 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2082 $skin = $wgUser->getSkin();
2084 $this->setRobotPolicy( 'noindex,nofollow' );
2085 $this->setArticleRelated( false );
2087 // If no reason is given, just supply a default "I can't let you do
2088 // that, Dave" message. Should only occur if called by legacy code.
2089 if ( $protected && empty( $reasons ) ) {
2090 $reasons[] = array( 'badaccess-group0' );
2093 if ( !empty( $reasons ) ) {
2094 // Permissions error
2096 $this->setPageTitle( wfMsg( 'viewsource' ) );
2098 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2101 $this->setPageTitle( wfMsg( 'badaccess' ) );
2103 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2105 // Wiki is read only
2106 $this->setPageTitle( wfMsg( 'readonly' ) );
2107 $reason = wfReadOnlyReason();
2108 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2111 // Show source, if supplied
2112 if( is_string( $source ) ) {
2113 $this->addWikiMsg( 'viewsourcetext' );
2116 'id' => 'wpTextbox1',
2117 'name' => 'wpTextbox1',
2118 'cols' => $wgUser->getOption( 'cols' ),
2119 'rows' => $wgUser->getOption( 'rows' ),
2120 'readonly' => 'readonly'
2122 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2124 // Show templates used by this article
2125 $skin = $wgUser->getSkin();
2126 $article = new Article( $this->getTitle() );
2127 $this->addHTML( "<div class='templatesUsed'>
2128 {$skin->formatTemplates( $article->getUsedTemplates() )}
2133 # If the title doesn't exist, it's fairly pointless to print a return
2134 # link to it. After all, you just tried editing it and couldn't, so
2135 # what's there to do there?
2136 if( $this->getTitle()->exists() ) {
2137 $this->returnToMain( null, $this->getTitle() );
2142 * Adds JS-based password security checker
2143 * @param $passwordId String ID of input box containing password
2144 * @param $retypeId String ID of input box containing retyped password
2147 public function addPasswordSecurity( $passwordId, $retypeId ) {
2149 'password' => '#' . $passwordId,
2150 'retype' => '#' . $retypeId,
2151 'messages' => array(),
2153 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2154 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2156 $data['messages'][$message] = wfMsg( $message );
2158 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2159 $this->addModules( 'mediawiki.legacy.password' );
2162 public function showFatalError( $message ) {
2163 $this->setPageTitle( wfMsg( 'internalerror' ) );
2164 $this->setRobotPolicy( 'noindex,nofollow' );
2165 $this->setArticleRelated( false );
2166 $this->enableClientCache( false );
2167 $this->mRedirect
= '';
2168 $this->mBodytext
= $message;
2171 public function showUnexpectedValueError( $name, $val ) {
2172 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2175 public function showFileCopyError( $old, $new ) {
2176 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2179 public function showFileRenameError( $old, $new ) {
2180 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2183 public function showFileDeleteError( $name ) {
2184 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2187 public function showFileNotFoundError( $name ) {
2188 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2192 * Add a "return to" link pointing to a specified title
2194 * @param $title Title to link
2195 * @param $query String: query string
2196 * @param $text String text of the link (input is not escaped)
2198 public function addReturnTo( $title, $query = array(), $text = null ) {
2200 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2203 $wgUser->getSkin()->link( $title, $text, array(), $query )
2205 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2209 * Add a "return to" link pointing to a specified title,
2210 * or the title indicated in the request, or else the main page
2212 * @param $unused No longer used
2213 * @param $returnto Title or String to return to
2214 * @param $returntoquery String: query string for the return to link
2216 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2219 if ( $returnto == null ) {
2220 $returnto = $wgRequest->getText( 'returnto' );
2223 if ( $returntoquery == null ) {
2224 $returntoquery = $wgRequest->getText( 'returntoquery' );
2227 if ( $returnto === '' ) {
2228 $returnto = Title
::newMainPage();
2231 if ( is_object( $returnto ) ) {
2232 $titleObj = $returnto;
2234 $titleObj = Title
::newFromText( $returnto );
2236 if ( !is_object( $titleObj ) ) {
2237 $titleObj = Title
::newMainPage();
2240 $this->addReturnTo( $titleObj, $returntoquery );
2244 * @param $sk Skin The given Skin
2245 * @param $includeStyle Boolean: unused
2246 * @return String: The doctype, opening <html>, and head element.
2248 public function headElement( Skin
$sk, $includeStyle = true ) {
2249 global $wgOutputEncoding, $wgMimeType;
2250 global $wgUseTrackbacks, $wgHtml5;
2251 global $wgUser, $wgRequest, $wgLang;
2253 if ( $sk->commonPrintStylesheet() ) {
2254 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2256 $sk->setupUserCss( $this );
2258 $ret = Html
::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2260 if ( $this->getHTMLTitle() == '' ) {
2261 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2264 $openHead = Html
::openElement( 'head' );
2266 # Don't bother with the newline if $head == ''
2267 $ret .= "$openHead\n";
2271 # More succinct than <meta http-equiv=Content-Type>, has the
2273 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2275 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2278 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2280 $ret .= implode( "\n", array(
2281 $this->getHeadLinks( $sk ),
2282 $this->buildCssLinks( $sk ),
2283 $this->getHeadItems()
2286 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2287 $ret .= $this->getTitle()->trackbackRDF();
2290 $closeHead = Html
::closeElement( 'head' );
2292 $ret .= "$closeHead\n";
2295 $bodyAttrs = array();
2297 # Crazy edit-on-double-click stuff
2298 $action = $wgRequest->getVal( 'action', 'view' );
2301 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2302 !in_array( $action, array( 'edit', 'submit' ) ) &&
2303 $wgUser->getOption( 'editondblclick' )
2306 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2310 $dir = wfUILang()->getDir();
2311 $bodyAttrs['class'] = "mediawiki $dir";
2313 if ( $wgLang->capitalizeAllNouns() ) {
2314 # A <body> class is probably not the best way to do this . . .
2315 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2317 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2318 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
2319 $bodyAttrs['class'] .= ' ns-special';
2320 } elseif ( $this->getTitle()->isTalkPage() ) {
2321 $bodyAttrs['class'] .= ' ns-talk';
2323 $bodyAttrs['class'] .= ' ns-subject';
2325 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2326 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
2328 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2329 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2331 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2337 * Get a ResourceLoader object associated with this OutputPage
2339 public function getResourceLoader() {
2340 if ( is_null( $this->mResourceLoader
) ) {
2341 $this->mResourceLoader
= new ResourceLoader();
2343 return $this->mResourceLoader
;
2349 * @param $modules Array/string with the module name
2350 * @param $only string May be styles, messages or scripts
2351 * @param $useESI boolean
2352 * @return string html <script> and <style> tags
2354 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2355 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2356 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2357 // Lazy-load ResourceLoader
2358 // TODO: Should this be a static function of ResourceLoader instead?
2359 // TODO: Divide off modules starting with "user", and add the user parameter to them
2361 'lang' => $wgLang->getCode(),
2362 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2363 'skin' => $skin->getSkinName(),
2366 // Propagate printable and handheld parameters if present
2367 if ( $wgRequest->getBool( 'printable' ) ) {
2368 $query['printable'] = 1;
2370 if ( $wgRequest->getBool( 'handheld' ) ) {
2371 $query['handheld'] = 1;
2374 if ( !count( $modules ) ) {
2378 if ( count( $modules ) > 1 ) {
2379 // Remove duplicate module requests
2380 $modules = array_unique( (array) $modules );
2381 // Sort module names so requests are more uniform
2384 if ( ResourceLoader
::inDebugMode() ) {
2385 // Recursively call us for every item
2387 foreach ( $modules as $name ) {
2388 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2394 // Create keyed-by-group list of module objects from modules list
2396 $resourceLoader = $this->getResourceLoader();
2397 foreach ( (array) $modules as $name ) {
2398 $module = $resourceLoader->getModule( $name );
2399 $group = $module->getGroup();
2400 if ( !isset( $groups[$group] ) ) {
2401 $groups[$group] = array();
2403 $groups[$group][$name] = $module;
2406 foreach ( $groups as $group => $modules ) {
2407 $query['modules'] = implode( '|', array_keys( $modules ) );
2408 // Special handling for user-specific groups
2409 if ( ( $group === 'user' ||
$group === 'private' ) && $wgUser->isLoggedIn() ) {
2410 $query['user'] = $wgUser->getName();
2412 // Support inlining of private modules if configured as such
2413 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2414 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2415 if ( $only == 'styles' ) {
2416 $links .= Html
::inlineStyle(
2417 $resourceLoader->makeModuleResponse( $context, $modules )
2420 $links .= Html
::inlineScript(
2421 ResourceLoader
::makeLoaderConditionalScript(
2422 $resourceLoader->makeModuleResponse( $context, $modules )
2428 // Special handling for user and site groups; because users might change their stuff
2429 // on-wiki like site or user pages, or user preferences; we need to find the highest
2430 // timestamp of these user-changable modules so we can ensure cache misses on change
2431 if ( $group === 'user' ||
$group === 'site' ) {
2432 // Create a fake request based on the one we are about to make so modules return
2434 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2435 // Get the maximum timestamp
2437 foreach ( $modules as $module ) {
2438 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2440 // Add a version parameter so cache will break when things change
2441 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, round( $timestamp, -2 ) );
2443 // Make queries uniform in order
2446 $url = wfAppendQuery( $wgLoadScript, $query );
2447 if ( $useESI && $wgResourceLoaderUseESI ) {
2448 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2449 if ( $only == 'styles' ) {
2450 $links .= Html
::inlineStyle( $esi );
2452 $links .= Html
::inlineScript( $esi );
2455 // Automatically select style/script elements
2456 if ( $only === 'styles' ) {
2457 $links .= Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2459 $links .= Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2467 * Gets the global variables and mScripts; also adds userjs to the end if
2468 * enabled. Despite the name, these scripts are no longer put in the
2469 * <head> but at the bottom of the <body>
2471 * @param $sk Skin object to use
2472 * @return String: HTML fragment
2474 function getHeadScripts( Skin
$sk ) {
2475 global $wgUser, $wgRequest, $wgUseSiteJs;
2477 // Startup - this will immediately load jquery and mediawiki modules
2478 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2480 // Configuration -- This could be merged together with the load and go, but
2481 // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
2482 $scripts .= Skin
::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2484 // Script and Messages "only" requests
2485 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2486 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2488 // Modules requests - let the client calculate dependencies and batch requests as it likes
2489 if ( $this->getModules() ) {
2490 $scripts .= Html
::inlineScript(
2491 ResourceLoader
::makeLoaderConditionalScript(
2492 Xml
::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
2493 Xml
::encodeJsCall( 'mediaWiki.loader.go', array() )
2499 $scripts .= "\n" . $this->mScripts
;
2501 // Add site JS if enabled
2502 if ( $wgUseSiteJs ) {
2503 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
2506 // Add user JS if enabled - trying to load user.options as a bundle if possible
2507 $userOptionsAdded = false;
2508 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2509 $action = $wgRequest->getVal( 'action', 'view' );
2510 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2511 # XXX: additional security check/prompt?
2512 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2514 $scripts .= $this->makeResourceLoaderLink(
2515 $sk, array( 'user', 'user.options' ), 'scripts'
2517 $userOptionsAdded = true;
2520 if ( !$userOptionsAdded ) {
2521 $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2528 * Add default \<meta\> tags
2530 protected function addDefaultMeta() {
2531 global $wgVersion, $wgHtml5;
2533 static $called = false;
2535 # Don't run this twice
2541 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2543 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2545 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2546 if( $p !== 'index,follow' ) {
2547 // http://www.robotstxt.org/wc/meta-user.html
2548 // Only show if it's different from the default robots policy
2549 $this->addMeta( 'robots', $p );
2552 if ( count( $this->mKeywords
) > 0 ) {
2554 "/<.*?" . ">/" => '',
2560 array_keys( $strip ),
2561 array_values( $strip ),
2562 implode( ',', $this->mKeywords
)
2569 * @return string HTML tag links to be put in the header.
2571 public function getHeadLinks( Skin
$sk ) {
2574 // Ideally this should happen earlier, somewhere. :P
2575 $this->addDefaultMeta();
2579 foreach ( $this->mMetatags
as $tag ) {
2580 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2582 $tag[0] = substr( $tag[0], 5 );
2586 $tags[] = Html
::element( 'meta',
2589 'content' => $tag[1]
2593 foreach ( $this->mLinktags
as $tag ) {
2594 $tags[] = Html
::element( 'link', $tag );
2598 foreach( $this->getSyndicationLinks() as $format => $link ) {
2599 # Use the page name for the title (accessed through $wgTitle since
2600 # there's no other way). In principle, this could lead to issues
2601 # with having the same name for different feeds corresponding to
2602 # the same page, but we can't avoid that at this low a level.
2604 $tags[] = $this->feedLink(
2607 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2608 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2612 # Recent changes feed should appear on every page (except recentchanges,
2613 # that would be redundant). Put it after the per-page feed to avoid
2614 # changing existing behavior. It's still available, probably via a
2615 # menu in your browser. Some sites might have a different feed they'd
2616 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2617 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2618 # If so, use it instead.
2620 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2621 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2623 if ( $wgOverrideSiteFeed ) {
2624 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2625 $tags[] = $this->feedLink(
2627 htmlspecialchars( $feedUrl ),
2628 wfMsg( "site-{$type}-feed", $wgSitename )
2631 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2632 foreach ( $wgAdvertisedFeedTypes as $format ) {
2633 $tags[] = $this->feedLink(
2635 $rctitle->getLocalURL( "feed={$format}" ),
2636 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2641 return implode( "\n", $tags );
2645 * Generate a <link rel/> for a feed.
2647 * @param $type String: feed type
2648 * @param $url String: URL to the feed
2649 * @param $text String: value of the "title" attribute
2650 * @return String: HTML fragment
2652 private function feedLink( $type, $url, $text ) {
2653 return Html
::element( 'link', array(
2654 'rel' => 'alternate',
2655 'type' => "application/$type+xml",
2662 * Add a local or specified stylesheet, with the given media options.
2663 * Meant primarily for internal use...
2665 * @param $style String: URL to the file
2666 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2667 * @param $condition String: for IE conditional comments, specifying an IE version
2668 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2670 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2672 // Even though we expect the media type to be lowercase, but here we
2673 // force it to lowercase to be safe.
2675 $options['media'] = $media;
2678 $options['condition'] = $condition;
2681 $options['dir'] = $dir;
2683 $this->styles
[$style] = $options;
2687 * Adds inline CSS styles
2688 * @param $style_css Mixed: inline CSS
2690 public function addInlineStyle( $style_css ){
2691 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2695 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2696 * These will be applied to various media & IE conditionals.
2697 * @param $sk Skin object
2699 public function buildCssLinks( $sk ) {
2701 // Add ResourceLoader styles
2702 // Split the styles into three groups
2703 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2704 $resourceLoader = $this->getResourceLoader();
2705 foreach ( $this->getModuleStyles() as $name ) {
2706 $group = $resourceLoader->getModule( $name )->getGroup();
2707 // Modules in groups named "other" or anything different than "user" or "site" will
2708 // be placed in the "other" group
2709 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2712 // We want site and user styles to override dynamically added styles from modules, but we want
2713 // dynamically added styles to override statically added styles from other modules. So the order
2714 // has to be other, dynamic, site, user
2715 // Add statically added styles for other modules
2716 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2717 // Add normal styles added through addStyle()/addInlineStyle() here
2718 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2719 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2720 // We use a <meta> tag with a made-up name for this because that's valid HTML
2721 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2722 // Add site and user styles
2723 $ret .= $this->makeResourceLoaderLink(
2724 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2729 public function buildCssLinksArray() {
2731 foreach( $this->styles
as $file => $options ) {
2732 $link = $this->styleLink( $file, $options );
2734 $links[$file] = $link;
2741 * Generate \<link\> tags for stylesheets
2743 * @param $style String: URL to the file
2744 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2746 * @return String: HTML fragment
2748 protected function styleLink( $style, $options ) {
2749 if( isset( $options['dir'] ) ) {
2750 $siteDir = wfUILang()->getDir();
2751 if( $siteDir != $options['dir'] ) {
2756 if( isset( $options['media'] ) ) {
2757 $media = self
::transformCssMedia( $options['media'] );
2758 if( is_null( $media ) ) {
2765 if( substr( $style, 0, 1 ) == '/' ||
2766 substr( $style, 0, 5 ) == 'http:' ||
2767 substr( $style, 0, 6 ) == 'https:' ) {
2770 global $wgStylePath, $wgStyleVersion;
2771 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2774 $link = Html
::linkedStyle( $url, $media );
2776 if( isset( $options['condition'] ) ) {
2777 $condition = htmlspecialchars( $options['condition'] );
2778 $link = "<!--[if $condition]>$link<![endif]-->";
2784 * Transform "media" attribute based on request parameters
2786 * @param $media String: current value of the "media" attribute
2787 * @return String: modified value of the "media" attribute
2789 public static function transformCssMedia( $media ) {
2790 global $wgRequest, $wgHandheldForIPhone;
2792 // Switch in on-screen display for media testing
2794 'printable' => 'print',
2795 'handheld' => 'handheld',
2797 foreach( $switches as $switch => $targetMedia ) {
2798 if( $wgRequest->getBool( $switch ) ) {
2799 if( $media == $targetMedia ) {
2801 } elseif( $media == 'screen' ) {
2807 // Expand longer media queries as iPhone doesn't grok 'handheld'
2808 if( $wgHandheldForIPhone ) {
2809 $mediaAliases = array(
2810 'screen' => 'screen and (min-device-width: 481px)',
2811 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2814 if( isset( $mediaAliases[$media] ) ) {
2815 $media = $mediaAliases[$media];
2823 * Turn off regular page output and return an error reponse
2824 * for when rate limiting has triggered.
2826 public function rateLimited() {
2827 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2828 $this->setRobotPolicy( 'noindex,follow' );
2829 $this->setArticleRelated( false );
2830 $this->enableClientCache( false );
2831 $this->mRedirect
= '';
2833 $this->setStatusCode( 503 );
2834 $this->addWikiMsg( 'actionthrottledtext' );
2836 $this->returnToMain( null, $this->getTitle() );
2840 * Show a warning about slave lag
2842 * If the lag is higher than $wgSlaveLagCritical seconds,
2843 * then the warning is a bit more obvious. If the lag is
2844 * lower than $wgSlaveLagWarning, then no warning is shown.
2846 * @param $lag Integer: slave lag
2848 public function showLagWarning( $lag ) {
2849 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2850 if( $lag >= $wgSlaveLagWarning ) {
2851 $message = $lag < $wgSlaveLagCritical
2854 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2855 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2860 * Add a wikitext-formatted message to the output.
2861 * This is equivalent to:
2863 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2865 public function addWikiMsg( /*...*/ ) {
2866 $args = func_get_args();
2867 $name = array_shift( $args );
2868 $this->addWikiMsgArray( $name, $args );
2872 * Add a wikitext-formatted message to the output.
2873 * Like addWikiMsg() except the parameters are taken as an array
2874 * instead of a variable argument list.
2876 * $options is passed through to wfMsgExt(), see that function for details.
2878 public function addWikiMsgArray( $name, $args, $options = array() ) {
2879 $options[] = 'parse';
2880 $text = wfMsgExt( $name, $options, $args );
2881 $this->addHTML( $text );
2885 * This function takes a number of message/argument specifications, wraps them in
2886 * some overall structure, and then parses the result and adds it to the output.
2888 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2889 * on. The subsequent arguments may either be strings, in which case they are the
2890 * message names, or arrays, in which case the first element is the message name,
2891 * and subsequent elements are the parameters to that message.
2893 * The special named parameter 'options' in a message specification array is passed
2894 * through to the $options parameter of wfMsgExt().
2896 * Don't use this for messages that are not in users interface language.
2900 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2904 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2906 * The newline after opening div is needed in some wikitext. See bug 19226.
2908 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2909 $msgSpecs = func_get_args();
2910 array_shift( $msgSpecs );
2911 $msgSpecs = array_values( $msgSpecs );
2913 foreach ( $msgSpecs as $n => $spec ) {
2915 if ( is_array( $spec ) ) {
2917 $name = array_shift( $args );
2918 if ( isset( $args['options'] ) ) {
2919 $options = $args['options'];
2920 unset( $args['options'] );
2926 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2928 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2932 * Include jQuery core. Use this to avoid loading it multiple times
2933 * before we get a usable script loader.
2935 * @param $modules Array: list of jQuery modules which should be loaded
2936 * @return Array: the list of modules which were not loaded.
2938 * @deprecated @since 1.17
2940 public function includeJQuery( $modules = array() ) {