2 if ( !defined( 'MEDIAWIKI' ) ) {
10 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
11 var $mExtStyles = array();
12 var $mPagetitle = '', $mBodytext = '';
15 * Holds the debug lines that will be outputted as comments in page source if
16 * $wgDebugComments is enabled. See also $wgShowDebug.
17 * TODO: make a getter method for this
19 public $mDebugtext = '';
21 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
22 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
23 var $mLastModified = '', $mETag = false;
24 var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
26 var $mScripts = '', $mInlineStyles = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
27 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
29 var $mInlineMsg = array();
31 var $mTemplateIds = array();
34 var $mSuppressQuickbar = false;
35 var $mDoNothing = false;
36 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
37 var $mIsArticleRelated = true;
38 protected $mParserOptions = null; // lazy initialised, use parserOptions()
40 var $mFeedLinks = array();
42 var $mEnableClientCache = true;
43 var $mArticleBodyOnly = false;
45 var $mNewSectionLink = false;
46 var $mHideNewSectionLink = false;
47 var $mNoGallery = false;
48 var $mPageTitleActionText = '';
49 var $mParseWarnings = array();
50 var $mSquidMaxage = 0;
51 var $mPreventClickjacking = true;
52 var $mRevisionId = null;
53 protected $mTitle = null;
56 * An array of stylesheet filenames (relative from skins path), with options
57 * for CSS media, IE conditions, and RTL/LTR direction.
58 * For internal use; add settings in the skin via $this->addStyle()
60 var $styles = array();
63 * Whether to load jQuery core.
65 protected $mJQueryDone = false;
67 private $mIndexPolicy = 'index';
68 private $mFollowPolicy = 'follow';
69 private $mVaryHeader = array(
70 'Accept-Encoding' => array( 'list-contains=gzip' ),
76 * Initialise private variables
78 function __construct() {
79 global $wgAllowUserJs;
80 $this->mAllowUserJs
= $wgAllowUserJs;
84 * Redirect to $url rather than displaying the normal page
86 * @param $url String: URL
87 * @param $responsecode String: HTTP status code
89 public function redirect( $url, $responsecode = '302' ) {
90 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
91 $this->mRedirect
= str_replace( "\n", '', $url );
92 $this->mRedirectCode
= $responsecode;
96 * Get the URL to redirect to, or an empty string if not redirect URL set
100 public function getRedirect() {
101 return $this->mRedirect
;
105 * Set the HTTP status code to send with the output.
107 * @param $statusCode Integer
110 public function setStatusCode( $statusCode ) {
111 $this->mStatusCode
= $statusCode;
115 * Add a new <meta> tag
116 * To add an http-equiv meta tag, precede the name with "http:"
118 * @param $name tag name
119 * @param $val tag value
121 function addMeta( $name, $val ) {
122 array_push( $this->mMetatags
, array( $name, $val ) );
126 * Add a keyword or a list of keywords in the page header
128 * @param $text String or array of strings
130 function addKeyword( $text ) {
131 if( is_array( $text ) ) {
132 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
134 array_push( $this->mKeywords
, $text );
139 * Add a new \<link\> tag to the page header
141 * @param $linkarr Array: associative array of attributes.
143 function addLink( $linkarr ) {
144 array_push( $this->mLinktags
, $linkarr );
148 * Add a new \<link\> with "rel" attribute set to "meta"
150 * @param $linkarr Array: associative array mapping attribute names to their
151 * values, both keys and values will be escaped, and the
152 * "rel" attribute will be automatically added
154 function addMetadataLink( $linkarr ) {
155 # note: buggy CC software only reads first "meta" link
156 static $haveMeta = false;
157 $linkarr['rel'] = $haveMeta ?
'alternate meta' : 'meta';
158 $this->addLink( $linkarr );
163 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
165 * @param $script String: raw HTML
167 function addScript( $script ) {
168 $this->mScripts
.= $script . "\n";
172 * Register and add a stylesheet from an extension directory.
174 * @param $url String path to sheet. Provide either a full url (beginning
175 * with 'http', etc) or a relative path from the document root
176 * (beginning with '/'). Otherwise it behaves identically to
177 * addStyle() and draws from the /skins folder.
179 public function addExtensionStyle( $url ) {
180 array_push( $this->mExtStyles
, $url );
184 * Get all links added by extensions
188 function getExtStyle() {
189 return $this->mExtStyles
;
193 * Add a JavaScript file out of skins/common, or a given relative path.
195 * @param $file String: filename in skins/common or complete on-server path
197 * @param $version String: style version of the file. Defaults to $wgStyleVersion
199 public function addScriptFile( $file, $version = null ) {
200 global $wgStylePath, $wgStyleVersion;
201 // See if $file parameter is an absolute URL or begins with a slash
202 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
205 $path = "{$wgStylePath}/common/{$file}";
207 if ( is_null( $version ) )
208 $version = $wgStyleVersion;
209 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
213 * Add a self-contained script tag with the given contents
215 * @param $script String: JavaScript text, no <script> tags
217 public function addInlineScript( $script ) {
218 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
222 * Get all registered JS and CSS tags for the header.
226 function getScript() {
227 return $this->mScripts
. $this->getHeadItems();
231 * Get the list of modules to include on this page
233 * @return Array of module names
235 public function getModules() {
236 return $this->mModules
;
240 * Add one or more modules recognized by the resource loader. Modules added
241 * through this function will be loaded by the resource loader when the
244 * @param $modules Mixed: module name (string) or array of module names
246 public function addModules( $modules ) {
247 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
251 * Get the list of module JS to include on this page
252 * @return array of module names
254 public function getModuleScripts() {
255 return $this->mModuleScripts
;
259 * Add only JS of one or more modules recognized by the resource loader. Module
260 * scripts added through this function will be loaded by the resource loader when
263 * @param $modules Mixed: module name (string) or array of module names
265 public function addModuleScripts( $modules ) {
266 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
270 * Get the list of module CSS to include on this page
272 * @return Array of module names
274 public function getModuleStyles() {
275 return $this->mModuleStyles
;
279 * Add only CSS of one or more modules recognized by the resource loader. Module
280 * styles added through this function will be loaded by the resource loader when
283 * @param $modules Mixed: module name (string) or array of module names
285 public function addModuleStyles( $modules ) {
286 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
290 * Get the list of module messages to include on this page
292 * @return Array of module names
294 public function getModuleMessages() {
295 return $this->mModuleMessages
;
299 * Add only messages of one or more modules recognized by the resource loader.
300 * Module messages added through this function will be loaded by the resource
301 * loader when the page loads.
303 * @param $modules Mixed: module name (string) or array of module names
305 public function addModuleMessages( $modules ) {
306 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
310 * Get all header items in a string
314 function getHeadItems() {
316 foreach ( $this->mHeadItems
as $item ) {
323 * Add or replace an header item to the output
325 * @param $name String: item name
326 * @param $value String: raw HTML
328 public function addHeadItem( $name, $value ) {
329 $this->mHeadItems
[$name] = $value;
333 * Check if the header item $name is already set
335 * @param $name String: item name
338 public function hasHeadItem( $name ) {
339 return isset( $this->mHeadItems
[$name] );
343 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
345 * @param $tag String: value of "ETag" header
347 function setETag( $tag ) {
352 * Set whether the output should only contain the body of the article,
353 * without any skin, sidebar, etc.
354 * Used e.g. when calling with "action=render".
356 * @param $only Boolean: whether to output only the body of the article
358 public function setArticleBodyOnly( $only ) {
359 $this->mArticleBodyOnly
= $only;
363 * Return whether the output will contain only the body of the article
367 public function getArticleBodyOnly() {
368 return $this->mArticleBodyOnly
;
372 * checkLastModified tells the client to use the client-cached page if
373 * possible. If sucessful, the OutputPage is disabled so that
374 * any future call to OutputPage->output() have no effect.
376 * Side effect: sets mLastModified for Last-Modified header
378 * @return Boolean: true iff cache-ok headers was sent.
380 public function checkLastModified( $timestamp ) {
381 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
383 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
384 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
387 if( !$wgCachePages ) {
388 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
391 if( $wgUser->getOption( 'nocache' ) ) {
392 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
396 $timestamp = wfTimestamp( TS_MW
, $timestamp );
397 $modifiedTimes = array(
398 'page' => $timestamp,
399 'user' => $wgUser->getTouched(),
400 'epoch' => $wgCacheEpoch
402 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
404 $maxModified = max( $modifiedTimes );
405 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
407 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
408 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
414 foreach ( $modifiedTimes as $name => $value ) {
415 if ( $info !== '' ) {
418 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
421 # IE sends sizes after the date like this:
422 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
423 # this breaks strtotime().
424 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
426 wfSuppressWarnings(); // E_STRICT system time bitching
427 $clientHeaderTime = strtotime( $clientHeader );
429 if ( !$clientHeaderTime ) {
430 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
433 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
435 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
436 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
437 wfDebug( __METHOD__
. ": effective Last-Modified: " .
438 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
439 if( $clientHeaderTime < $maxModified ) {
440 wfDebug( __METHOD__
. ": STALE, $info\n", false );
445 # Give a 304 response code and disable body output
446 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
447 ini_set( 'zlib.output_compression', 0 );
448 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
449 $this->sendCacheControl();
452 // Don't output a compressed blob when using ob_gzhandler;
453 // it's technically against HTTP spec and seems to confuse
454 // Firefox when the response gets split over two packets.
455 wfClearOutputBuffers();
461 * Override the last modified timestamp
463 * @param $timestamp String: new timestamp, in a format readable by
466 public function setLastModified( $timestamp ) {
467 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
471 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
473 * @param $policy String: the literal string to output as the contents of
474 * the meta tag. Will be parsed according to the spec and output in
478 public function setRobotPolicy( $policy ) {
479 $policy = Article
::formatRobotPolicy( $policy );
481 if( isset( $policy['index'] ) ) {
482 $this->setIndexPolicy( $policy['index'] );
484 if( isset( $policy['follow'] ) ) {
485 $this->setFollowPolicy( $policy['follow'] );
490 * Set the index policy for the page, but leave the follow policy un-
493 * @param $policy string Either 'index' or 'noindex'.
496 public function setIndexPolicy( $policy ) {
497 $policy = trim( $policy );
498 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
499 $this->mIndexPolicy
= $policy;
504 * Set the follow policy for the page, but leave the index policy un-
507 * @param $policy String: either 'follow' or 'nofollow'.
510 public function setFollowPolicy( $policy ) {
511 $policy = trim( $policy );
512 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
513 $this->mFollowPolicy
= $policy;
518 * Set the new value of the "action text", this will be added to the
519 * "HTML title", separated from it with " - ".
521 * @param $text String: new value of the "action text"
523 public function setPageTitleActionText( $text ) {
524 $this->mPageTitleActionText
= $text;
528 * Get the value of the "action text"
532 public function getPageTitleActionText() {
533 if ( isset( $this->mPageTitleActionText
) ) {
534 return $this->mPageTitleActionText
;
539 * "HTML title" means the contents of <title>.
540 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
542 public function setHTMLTitle( $name ) {
543 $this->mHTMLtitle
= $name;
547 * Return the "HTML title", i.e. the content of the <title> tag.
551 public function getHTMLTitle() {
552 return $this->mHTMLtitle
;
556 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
557 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
558 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
559 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
561 public function setPageTitle( $name ) {
562 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
563 # but leave "<i>foobar</i>" alone
564 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
565 $this->mPagetitle
= $nameWithTags;
567 # change "<i>foo&bar</i>" to "foo&bar"
568 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
572 * Return the "page title", i.e. the content of the \<h1\> tag.
576 public function getPageTitle() {
577 return $this->mPagetitle
;
581 * Set the Title object to use
583 * @param $t Title object
585 public function setTitle( $t ) {
590 * Get the Title object used in this instance
594 public function getTitle() {
595 if ( $this->mTitle
instanceof Title
) {
596 return $this->mTitle
;
598 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
605 * Replace the subtile with $str
607 * @param $str String: new value of the subtitle
609 public function setSubtitle( $str ) {
610 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
614 * Add $str to the subtitle
616 * @param $str String to add to the subtitle
618 public function appendSubtitle( $str ) {
619 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
627 public function getSubtitle() {
628 return $this->mSubtitle
;
632 * Set the page as printable, i.e. it'll be displayed with with all
633 * print styles included
635 public function setPrintable() {
636 $this->mPrintable
= true;
640 * Return whether the page is "printable"
644 public function isPrintable() {
645 return $this->mPrintable
;
649 * Disable output completely, i.e. calling output() will have no effect
651 public function disable() {
652 $this->mDoNothing
= true;
656 * Return whether the output will be completely disabled
660 public function isDisabled() {
661 return $this->mDoNothing
;
665 * Show an "add new section" link?
669 public function showNewSectionLink() {
670 return $this->mNewSectionLink
;
674 * Forcibly hide the new section link?
678 public function forceHideNewSectionLink() {
679 return $this->mHideNewSectionLink
;
683 * Add or remove feed links in the page header
684 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
685 * for the new version
688 * @param $show Boolean: true: add default feeds, false: remove all feeds
690 public function setSyndicated( $show = true ) {
692 $this->setFeedAppendQuery( false );
694 $this->mFeedLinks
= array();
699 * Add default feeds to the page header
700 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
701 * for the new version
704 * @param $val String: query to append to feed links or false to output
707 public function setFeedAppendQuery( $val ) {
708 global $wgAdvertisedFeedTypes;
710 $this->mFeedLinks
= array();
712 foreach ( $wgAdvertisedFeedTypes as $type ) {
713 $query = "feed=$type";
714 if ( is_string( $val ) ) {
715 $query .= '&' . $val;
717 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
722 * Add a feed link to the page header
724 * @param $format String: feed type, should be a key of $wgFeedClasses
725 * @param $href String: URL
727 public function addFeedLink( $format, $href ) {
728 global $wgAdvertisedFeedTypes;
730 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
731 $this->mFeedLinks
[$format] = $href;
736 * Should we output feed links for this page?
739 public function isSyndicated() {
740 return count( $this->mFeedLinks
) > 0;
744 * Return URLs for each supported syndication format for this page.
745 * @return array associating format keys with URLs
747 public function getSyndicationLinks() {
748 return $this->mFeedLinks
;
752 * Will currently always return null
756 public function getFeedAppendQuery() {
757 return $this->mFeedLinksAppendQuery
;
761 * Set whether the displayed content is related to the source of the
762 * corresponding article on the wiki
763 * Setting true will cause the change "article related" toggle to true
767 public function setArticleFlag( $v ) {
768 $this->mIsarticle
= $v;
770 $this->mIsArticleRelated
= $v;
775 * Return whether the content displayed page is related to the source of
776 * the corresponding article on the wiki
780 public function isArticle() {
781 return $this->mIsarticle
;
785 * Set whether this page is related an article on the wiki
786 * Setting false will cause the change of "article flag" toggle to false
790 public function setArticleRelated( $v ) {
791 $this->mIsArticleRelated
= $v;
793 $this->mIsarticle
= false;
798 * Return whether this page is related an article on the wiki
802 public function isArticleRelated() {
803 return $this->mIsArticleRelated
;
807 * Add new language links
809 * @param $newLinkArray Associative array mapping language code to the page
812 public function addLanguageLinks( $newLinkArray ) {
813 $this->mLanguageLinks +
= $newLinkArray;
817 * Reset the language links and add new language links
819 * @param $newLinkArray Associative array mapping language code to the page
822 public function setLanguageLinks( $newLinkArray ) {
823 $this->mLanguageLinks
= $newLinkArray;
827 * Get the list of language links
829 * @return Associative array mapping language code to the page name
831 public function getLanguageLinks() {
832 return $this->mLanguageLinks
;
836 * Add an array of categories, with names in the keys
838 * @param $categories Associative array mapping category name to its sort key
840 public function addCategoryLinks( $categories ) {
841 global $wgUser, $wgContLang;
843 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
847 # Add the links to a LinkBatch
848 $arr = array( NS_CATEGORY
=> $categories );
850 $lb->setArray( $arr );
852 # Fetch existence plus the hiddencat property
853 $dbr = wfGetDB( DB_SLAVE
);
854 $pageTable = $dbr->tableName( 'page' );
855 $where = $lb->constructSet( 'page', $dbr );
856 $propsTable = $dbr->tableName( 'page_props' );
857 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
858 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
859 $res = $dbr->query( $sql, __METHOD__
);
861 # Add the results to the link cache
862 $lb->addResultToCache( LinkCache
::singleton(), $res );
864 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
865 $categories = array_combine(
866 array_keys( $categories ),
867 array_fill( 0, count( $categories ), 'normal' )
870 # Mark hidden categories
871 foreach ( $res as $row ) {
872 if ( isset( $row->pp_value
) ) {
873 $categories[$row->page_title
] = 'hidden';
877 # Add the remaining categories to the skin
878 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
879 $sk = $wgUser->getSkin();
880 foreach ( $categories as $category => $type ) {
881 $origcategory = $category;
882 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
883 $wgContLang->findVariantLink( $category, $title, true );
884 if ( $category != $origcategory ) {
885 if ( array_key_exists( $category, $categories ) ) {
889 $text = $wgContLang->convertHtml( $title->getText() );
890 $this->mCategories
[] = $title->getText();
891 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
897 * Reset the category links (but not the category list) and add $categories
899 * @param $categories Associative array mapping category name to its sort key
901 public function setCategoryLinks( $categories ) {
902 $this->mCategoryLinks
= array();
903 $this->addCategoryLinks( $categories );
907 * Get the list of category links, in a 2-D array with the following format:
908 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
909 * hidden categories) and $link a HTML fragment with a link to the category
914 public function getCategoryLinks() {
915 return $this->mCategoryLinks
;
919 * Get the list of category names this page belongs to
921 * @return Array of strings
923 public function getCategories() {
924 return $this->mCategories
;
928 * Suppress the quickbar from the output, only for skin supporting
931 public function suppressQuickbar() {
932 $this->mSuppressQuickbar
= true;
936 * Return whether the quickbar should be suppressed from the output
940 public function isQuickbarSuppressed() {
941 return $this->mSuppressQuickbar
;
945 * Remove user JavaScript from scripts to load
947 public function disallowUserJs() {
948 $this->mAllowUserJs
= false;
952 * Return whether user JavaScript is allowed for this page
956 public function isUserJsAllowed() {
957 return $this->mAllowUserJs
;
961 * Prepend $text to the body HTML
963 * @param $text String: HTML
965 public function prependHTML( $text ) {
966 $this->mBodytext
= $text . $this->mBodytext
;
970 * Append $text to the body HTML
972 * @param $text String: HTML
974 public function addHTML( $text ) {
975 $this->mBodytext
.= $text;
979 * Clear the body HTML
981 public function clearHTML() {
982 $this->mBodytext
= '';
988 * @return String: HTML
990 public function getHTML() {
991 return $this->mBodytext
;
995 * Add $text to the debug output
997 * @param $text String: debug text
999 public function debug( $text ) {
1000 $this->mDebugtext
.= $text;
1004 * Get/set the ParserOptions object to use for wikitext parsing
1006 * @param $options either the ParserOption to use or null to only get the
1007 * current ParserOption object
1008 * @return current ParserOption object
1010 public function parserOptions( $options = null ) {
1011 if ( !$this->mParserOptions
) {
1012 $this->mParserOptions
= new ParserOptions
;
1014 return wfSetVar( $this->mParserOptions
, $options );
1018 * Set the revision ID which will be seen by the wiki text parser
1019 * for things such as embedded {{REVISIONID}} variable use.
1021 * @param $revid Mixed: an positive integer, or null
1022 * @return Mixed: previous value
1024 public function setRevisionId( $revid ) {
1025 $val = is_null( $revid ) ?
null : intval( $revid );
1026 return wfSetVar( $this->mRevisionId
, $val );
1030 * Get the current revision ID
1034 public function getRevisionId() {
1035 return $this->mRevisionId
;
1039 * Convert wikitext to HTML and add it to the buffer
1040 * Default assumes that the current page title will be used.
1042 * @param $text String
1043 * @param $linestart Boolean: is this the start of a line?
1045 public function addWikiText( $text, $linestart = true ) {
1046 $title = $this->getTitle(); // Work arround E_STRICT
1047 $this->addWikiTextTitle( $text, $title, $linestart );
1051 * Add wikitext with a custom Title object
1053 * @param $text String: wikitext
1054 * @param $title Title object
1055 * @param $linestart Boolean: is this the start of a line?
1057 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1058 $this->addWikiTextTitle( $text, $title, $linestart );
1062 * Add wikitext with a custom Title object and
1064 * @param $text String: wikitext
1065 * @param $title Title object
1066 * @param $linestart Boolean: is this the start of a line?
1068 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1069 $this->addWikiTextTitle( $text, $title, $linestart, true );
1073 * Add wikitext with tidy enabled
1075 * @param $text String: wikitext
1076 * @param $linestart Boolean: is this the start of a line?
1078 public function addWikiTextTidy( $text, $linestart = true ) {
1079 $title = $this->getTitle();
1080 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1084 * Add wikitext with a custom Title object
1086 * @param $text String: wikitext
1087 * @param $title Title object
1088 * @param $linestart Boolean: is this the start of a line?
1089 * @param $tidy Boolean: whether to use tidy
1091 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1094 wfProfileIn( __METHOD__
);
1096 wfIncrStats( 'pcache_not_possible' );
1098 $popts = $this->parserOptions();
1099 $oldTidy = $popts->setTidy( $tidy );
1101 $parserOutput = $wgParser->parse(
1102 $text, $title, $popts,
1103 $linestart, true, $this->mRevisionId
1106 $popts->setTidy( $oldTidy );
1108 $this->addParserOutput( $parserOutput );
1110 wfProfileOut( __METHOD__
);
1114 * Add a ParserOutput object, but without Html
1116 * @param $parserOutput ParserOutput object
1118 public function addParserOutputNoText( &$parserOutput ) {
1119 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1120 $this->addCategoryLinks( $parserOutput->getCategories() );
1121 $this->mNewSectionLink
= $parserOutput->getNewSection();
1122 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1124 $this->mParseWarnings
= $parserOutput->getWarnings();
1125 if ( !$parserOutput->isCacheable() ) {
1126 $this->enableClientCache( false );
1128 $this->mNoGallery
= $parserOutput->getNoGallery();
1129 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1130 $this->addModules( $parserOutput->getModules() );
1132 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1133 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1134 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1136 $this->mTemplateIds
[$ns] = $dbks;
1140 // Hooks registered in the object
1141 global $wgParserOutputHooks;
1142 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1143 list( $hookName, $data ) = $hookInfo;
1144 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1145 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1149 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1153 * Add a ParserOutput object
1155 * @param $parserOutput ParserOutput
1157 function addParserOutput( &$parserOutput ) {
1158 $this->addParserOutputNoText( $parserOutput );
1159 $text = $parserOutput->getText();
1160 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1161 $this->addHTML( $text );
1166 * Add the output of a QuickTemplate to the output buffer
1168 * @param $template QuickTemplate
1170 public function addTemplate( &$template ) {
1172 $template->execute();
1173 $this->addHTML( ob_get_contents() );
1178 * Parse wikitext and return the HTML.
1180 * @param $text String
1181 * @param $linestart Boolean: is this the start of a line?
1182 * @param $interface Boolean: use interface language ($wgLang instead of
1183 * $wgContLang) while parsing language sensitive magic
1184 * words like GRAMMAR and PLURAL
1185 * @param $language Language object: target language object, will override
1187 * @return String: HTML
1189 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1192 if( is_null( $this->getTitle() ) ) {
1193 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1196 $popts = $this->parserOptions();
1198 $popts->setInterfaceMessage( true );
1200 if ( $language !== null ) {
1201 $oldLang = $popts->setTargetLanguage( $language );
1204 $parserOutput = $wgParser->parse(
1205 $text, $this->getTitle(), $popts,
1206 $linestart, true, $this->mRevisionId
1210 $popts->setInterfaceMessage( false );
1212 if ( $language !== null ) {
1213 $popts->setTargetLanguage( $oldLang );
1216 return $parserOutput->getText();
1220 * Parse wikitext, strip paragraphs, and return the HTML.
1222 * @param $text String
1223 * @param $linestart Boolean: is this the start of a line?
1224 * @param $interface Boolean: use interface language ($wgLang instead of
1225 * $wgContLang) while parsing language sensitive magic
1226 * words like GRAMMAR and PLURAL
1227 * @return String: HTML
1229 public function parseInline( $text, $linestart = true, $interface = false ) {
1230 $parsed = $this->parse( $text, $linestart, $interface );
1233 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1241 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1243 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1245 public function setSquidMaxage( $maxage ) {
1246 $this->mSquidMaxage
= $maxage;
1250 * Use enableClientCache(false) to force it to send nocache headers
1254 public function enableClientCache( $state ) {
1255 return wfSetVar( $this->mEnableClientCache
, $state );
1259 * Get the list of cookies that will influence on the cache
1263 function getCacheVaryCookies() {
1264 global $wgCookiePrefix, $wgCacheVaryCookies;
1266 if ( $cookies === null ) {
1267 $cookies = array_merge(
1269 "{$wgCookiePrefix}Token",
1270 "{$wgCookiePrefix}LoggedOut",
1275 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1281 * Return whether this page is not cacheable because "useskin" or "uselang"
1282 * URL parameters were passed.
1286 function uncacheableBecauseRequestVars() {
1288 return $wgRequest->getText( 'useskin', false ) === false
1289 && $wgRequest->getText( 'uselang', false ) === false;
1293 * Check if the request has a cache-varying cookie header
1294 * If it does, it's very important that we don't allow public caching
1298 function haveCacheVaryCookies() {
1300 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1301 if ( $cookieHeader === false ) {
1304 $cvCookies = $this->getCacheVaryCookies();
1305 foreach ( $cvCookies as $cookieName ) {
1306 # Check for a simple string match, like the way squid does it
1307 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1308 wfDebug( __METHOD__
. ": found $cookieName\n" );
1312 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1317 * Add an HTTP header that will influence on the cache
1319 * @param $header String: header name
1320 * @param $option either an Array or null
1322 public function addVaryHeader( $header, $option = null ) {
1323 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1324 $this->mVaryHeader
[$header] = $option;
1325 } elseif( is_array( $option ) ) {
1326 if( is_array( $this->mVaryHeader
[$header] ) ) {
1327 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1329 $this->mVaryHeader
[$header] = $option;
1332 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1336 * Get a complete X-Vary-Options header
1340 public function getXVO() {
1341 $cvCookies = $this->getCacheVaryCookies();
1343 $cookiesOption = array();
1344 foreach ( $cvCookies as $cookieName ) {
1345 $cookiesOption[] = 'string-contains=' . $cookieName;
1347 $this->addVaryHeader( 'Cookie', $cookiesOption );
1350 foreach( $this->mVaryHeader
as $header => $option ) {
1351 $newheader = $header;
1352 if( is_array( $option ) ) {
1353 $newheader .= ';' . implode( ';', $option );
1355 $headers[] = $newheader;
1357 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1363 * bug 21672: Add Accept-Language to Vary and XVO headers
1364 * if there's no 'variant' parameter existed in GET.
1367 * /w/index.php?title=Main_page should always be served; but
1368 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1370 function addAcceptLanguage() {
1371 global $wgRequest, $wgContLang;
1372 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1373 $variants = $wgContLang->getVariants();
1374 $aloption = array();
1375 foreach ( $variants as $variant ) {
1376 if( $variant === $wgContLang->getCode() ) {
1379 $aloption[] = 'string-contains=' . $variant;
1381 // IE and some other browsers use another form of language code
1382 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1383 // We should handle these too.
1384 $ievariant = explode( '-', $variant );
1385 if ( count( $ievariant ) == 2 ) {
1386 $ievariant[1] = strtoupper( $ievariant[1] );
1387 $ievariant = implode( '-', $ievariant );
1388 $aloption[] = 'string-contains=' . $ievariant;
1392 $this->addVaryHeader( 'Accept-Language', $aloption );
1397 * Set a flag which will cause an X-Frame-Options header appropriate for
1398 * edit pages to be sent. The header value is controlled by
1399 * $wgEditPageFrameOptions.
1401 * This is the default for special pages. If you display a CSRF-protected
1402 * form on an ordinary view page, then you need to call this function.
1404 public function preventClickjacking( $enable = true ) {
1405 $this->mPreventClickjacking
= $enable;
1409 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1410 * This can be called from pages which do not contain any CSRF-protected
1413 public function allowClickjacking() {
1414 $this->mPreventClickjacking
= false;
1418 * Get the X-Frame-Options header value (without the name part), or false
1419 * if there isn't one. This is used by Skin to determine whether to enable
1420 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1422 public function getFrameOptions() {
1423 global $wgBreakFrames, $wgEditPageFrameOptions;
1424 if ( $wgBreakFrames ) {
1426 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1427 return $wgEditPageFrameOptions;
1432 * Send cache control HTTP headers
1434 public function sendCacheControl() {
1435 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1437 $response = $wgRequest->response();
1438 if ( $wgUseETag && $this->mETag
) {
1439 $response->header( "ETag: $this->mETag" );
1442 $this->addAcceptLanguage();
1444 # don't serve compressed data to clients who can't handle it
1445 # maintain different caches for logged-in users and non-logged in ones
1446 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1449 # Add an X-Vary-Options header for Squid with Wikimedia patches
1450 $response->header( $this->getXVO() );
1453 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1455 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1456 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1460 # We'll purge the proxy cache explicitly, but require end user agents
1461 # to revalidate against the proxy on each visit.
1462 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1463 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1464 # start with a shorter timeout for initial testing
1465 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1466 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1467 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1469 # We'll purge the proxy cache for anons explicitly, but require end user agents
1470 # to revalidate against the proxy on each visit.
1471 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1472 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1473 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1474 # start with a shorter timeout for initial testing
1475 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1476 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1479 # We do want clients to cache if they can, but they *must* check for updates
1480 # on revisiting the page.
1481 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1482 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1483 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1485 if($this->mLastModified
) {
1486 $response->header( "Last-Modified: {$this->mLastModified}" );
1489 wfDebug( __METHOD__
. ": no caching **\n", false );
1491 # In general, the absence of a last modified header should be enough to prevent
1492 # the client from using its cache. We send a few other things just to make sure.
1493 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1494 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1495 $response->header( 'Pragma: no-cache' );
1500 * Get the message associed with the HTTP response code $code
1502 * @param $code Integer: status code
1503 * @return String or null: message or null if $code is not in the list of
1506 public static function getStatusMessage( $code ) {
1507 static $statusMessage = array(
1509 101 => 'Switching Protocols',
1510 102 => 'Processing',
1514 203 => 'Non-Authoritative Information',
1515 204 => 'No Content',
1516 205 => 'Reset Content',
1517 206 => 'Partial Content',
1518 207 => 'Multi-Status',
1519 300 => 'Multiple Choices',
1520 301 => 'Moved Permanently',
1523 304 => 'Not Modified',
1525 307 => 'Temporary Redirect',
1526 400 => 'Bad Request',
1527 401 => 'Unauthorized',
1528 402 => 'Payment Required',
1531 405 => 'Method Not Allowed',
1532 406 => 'Not Acceptable',
1533 407 => 'Proxy Authentication Required',
1534 408 => 'Request Timeout',
1537 411 => 'Length Required',
1538 412 => 'Precondition Failed',
1539 413 => 'Request Entity Too Large',
1540 414 => 'Request-URI Too Large',
1541 415 => 'Unsupported Media Type',
1542 416 => 'Request Range Not Satisfiable',
1543 417 => 'Expectation Failed',
1544 422 => 'Unprocessable Entity',
1546 424 => 'Failed Dependency',
1547 500 => 'Internal Server Error',
1548 501 => 'Not Implemented',
1549 502 => 'Bad Gateway',
1550 503 => 'Service Unavailable',
1551 504 => 'Gateway Timeout',
1552 505 => 'HTTP Version Not Supported',
1553 507 => 'Insufficient Storage'
1555 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1559 * Finally, all the text has been munged and accumulated into
1560 * the object, let's actually output it:
1562 public function output() {
1563 global $wgUser, $wgOutputEncoding, $wgRequest;
1564 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1565 global $wgUseAjax, $wgAjaxWatch;
1566 global $wgEnableMWSuggest, $wgUniversalEditButton;
1568 if( $this->mDoNothing
) {
1571 wfProfileIn( __METHOD__
);
1572 if ( $this->mRedirect
!= '' ) {
1573 # Standards require redirect URLs to be absolute
1574 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1575 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1576 if( !$wgDebugRedirects ) {
1577 $message = self
::getStatusMessage( $this->mRedirectCode
);
1578 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1580 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1582 $this->sendCacheControl();
1584 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1585 if( $wgDebugRedirects ) {
1586 $url = htmlspecialchars( $this->mRedirect
);
1587 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1588 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1589 print "</body>\n</html>\n";
1591 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1593 wfProfileOut( __METHOD__
);
1595 } elseif ( $this->mStatusCode
) {
1596 $message = self
::getStatusMessage( $this->mStatusCode
);
1598 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1602 $sk = $wgUser->getSkin();
1604 // Add base resources
1605 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1607 // Add various resources if required
1609 $this->addModules( 'mediawiki.legacy.ajax' );
1611 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1613 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1614 $this->addModules( 'mediawiki.action.watch.ajax' );
1617 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1618 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1622 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1623 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1626 if( $wgUniversalEditButton ) {
1627 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1628 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1629 // Original UniversalEditButton
1630 $msg = wfMsg( 'edit' );
1631 $this->addLink( array(
1632 'rel' => 'alternate',
1633 'type' => 'application/x-wiki',
1635 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1637 // Alternate edit link
1638 $this->addLink( array(
1641 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1647 # Buffer output; final headers may depend on later processing
1650 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1651 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1653 // Prevent framing, if requested
1654 $frameOptions = $this->getFrameOptions();
1655 if ( $frameOptions ) {
1656 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1659 if ( $this->mArticleBodyOnly
) {
1660 $this->out( $this->mBodytext
);
1662 // Hook that allows last minute changes to the output page, e.g.
1663 // adding of CSS or Javascript by extensions.
1664 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1666 wfProfileIn( 'Output-skin' );
1667 $sk->outputPage( $this );
1668 wfProfileOut( 'Output-skin' );
1671 $this->sendCacheControl();
1673 wfProfileOut( __METHOD__
);
1677 * Actually output something with print(). Performs an iconv to the
1678 * output encoding, if needed.
1680 * @param $ins String: the string to output
1682 public function out( $ins ) {
1683 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1684 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1687 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1688 if ( false === $outs ) {
1696 * Produce a "user is blocked" page.
1698 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1701 function blockedPage( $return = true ) {
1702 global $wgUser, $wgContLang, $wgLang;
1704 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1705 $this->setRobotPolicy( 'noindex,nofollow' );
1706 $this->setArticleRelated( false );
1708 $name = User
::whoIs( $wgUser->blockedBy() );
1709 $reason = $wgUser->blockedFor();
1710 if( $reason == '' ) {
1711 $reason = wfMsg( 'blockednoreason' );
1713 $blockTimestamp = $wgLang->timeanddate(
1714 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1718 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1720 $blockid = $wgUser->mBlock
->mId
;
1722 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1723 if ( $blockExpiry == 'infinity' ) {
1724 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1725 // Search for localization in 'ipboptions'
1726 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1727 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1728 if ( strpos( $option, ':' ) === false ) {
1731 list( $show, $value ) = explode( ':', $option );
1732 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1733 $blockExpiry = $show;
1738 $blockExpiry = $wgLang->timeanddate(
1739 wfTimestamp( TS_MW
, $blockExpiry ),
1744 if ( $wgUser->mBlock
->mAuto
) {
1745 $msg = 'autoblockedtext';
1747 $msg = 'blockedtext';
1750 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1751 * This could be a username, an IP range, or a single IP. */
1752 $intended = $wgUser->mBlock
->mAddress
;
1755 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1756 $intended, $blockTimestamp
1759 # Don't auto-return to special pages
1761 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1762 $this->returnToMain( null, $return );
1767 * Output a standard error page
1769 * @param $title String: message key for page title
1770 * @param $msg String: message key for page text
1771 * @param $params Array: message parameters
1773 public function showErrorPage( $title, $msg, $params = array() ) {
1774 if ( $this->getTitle() ) {
1775 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1777 $this->setPageTitle( wfMsg( $title ) );
1778 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1779 $this->setRobotPolicy( 'noindex,nofollow' );
1780 $this->setArticleRelated( false );
1781 $this->enableClientCache( false );
1782 $this->mRedirect
= '';
1783 $this->mBodytext
= '';
1785 $this->addWikiMsgArray( $msg, $params );
1787 $this->returnToMain();
1791 * Output a standard permission error page
1793 * @param $errors Array: error message keys
1794 * @param $action String: action that was denied or null if unknown
1796 public function showPermissionsErrorPage( $errors, $action = null ) {
1797 $this->mDebugtext
.= 'Original title: ' .
1798 $this->getTitle()->getPrefixedText() . "\n";
1799 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1800 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1801 $this->setRobotPolicy( 'noindex,nofollow' );
1802 $this->setArticleRelated( false );
1803 $this->enableClientCache( false );
1804 $this->mRedirect
= '';
1805 $this->mBodytext
= '';
1806 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1810 * Display an error page indicating that a given version of MediaWiki is
1811 * required to use it
1813 * @param $version Mixed: the version of MediaWiki needed to use the page
1815 public function versionRequired( $version ) {
1816 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1817 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1818 $this->setRobotPolicy( 'noindex,nofollow' );
1819 $this->setArticleRelated( false );
1820 $this->mBodytext
= '';
1822 $this->addWikiMsg( 'versionrequiredtext', $version );
1823 $this->returnToMain();
1827 * Display an error page noting that a given permission bit is required.
1829 * @param $permission String: key required
1831 public function permissionRequired( $permission ) {
1834 $this->setPageTitle( wfMsg( 'badaccess' ) );
1835 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1836 $this->setRobotPolicy( 'noindex,nofollow' );
1837 $this->setArticleRelated( false );
1838 $this->mBodytext
= '';
1840 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1841 User
::getGroupsWithPermission( $permission ) );
1845 $wgLang->commaList( $groups ),
1849 $this->addWikiMsg( 'badaccess-group0' );
1851 $this->returnToMain();
1855 * Produce the stock "please login to use the wiki" page
1857 public function loginToUse() {
1860 if( $wgUser->isLoggedIn() ) {
1861 $this->permissionRequired( 'read' );
1865 $skin = $wgUser->getSkin();
1867 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1868 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1869 $this->setRobotPolicy( 'noindex,nofollow' );
1870 $this->setArticleRelated( false );
1872 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1873 $loginLink = $skin->link(
1875 wfMsgHtml( 'loginreqlink' ),
1877 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1878 array( 'known', 'noclasses' )
1880 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1881 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1883 # Don't return to the main page if the user can't read it
1884 # otherwise we'll end up in a pointless loop
1885 $mainPage = Title
::newMainPage();
1886 if( $mainPage->userCanRead() ) {
1887 $this->returnToMain( null, $mainPage );
1892 * Format a list of error messages
1894 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1895 * @param $action String: action that was denied or null if unknown
1896 * @return String: the wikitext error-messages, formatted into a list.
1898 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1899 if ( $action == null ) {
1900 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1902 $action_desc = wfMsgNoTrans( "action-$action" );
1903 $text = wfMsgNoTrans(
1904 'permissionserrorstext-withaction',
1910 if ( count( $errors ) > 1 ) {
1911 $text .= '<ul class="permissions-errors">' . "\n";
1913 foreach( $errors as $error ) {
1915 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1920 $text .= "<div class=\"permissions-errors\">\n" .
1921 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
1929 * Display a page stating that the Wiki is in read-only mode,
1930 * and optionally show the source of the page that the user
1931 * was trying to edit. Should only be called (for this
1932 * purpose) after wfReadOnly() has returned true.
1934 * For historical reasons, this function is _also_ used to
1935 * show the error message when a user tries to edit a page
1936 * they are not allowed to edit. (Unless it's because they're
1937 * blocked, then we show blockedPage() instead.) In this
1938 * case, the second parameter should be set to true and a list
1939 * of reasons supplied as the third parameter.
1941 * @todo Needs to be split into multiple functions.
1943 * @param $source String: source code to show (or null).
1944 * @param $protected Boolean: is this a permissions error?
1945 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1946 * @param $action String: action that was denied or null if unknown
1948 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1950 $skin = $wgUser->getSkin();
1952 $this->setRobotPolicy( 'noindex,nofollow' );
1953 $this->setArticleRelated( false );
1955 // If no reason is given, just supply a default "I can't let you do
1956 // that, Dave" message. Should only occur if called by legacy code.
1957 if ( $protected && empty( $reasons ) ) {
1958 $reasons[] = array( 'badaccess-group0' );
1961 if ( !empty( $reasons ) ) {
1962 // Permissions error
1964 $this->setPageTitle( wfMsg( 'viewsource' ) );
1966 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
1969 $this->setPageTitle( wfMsg( 'badaccess' ) );
1971 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1973 // Wiki is read only
1974 $this->setPageTitle( wfMsg( 'readonly' ) );
1975 $reason = wfReadOnlyReason();
1976 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
1979 // Show source, if supplied
1980 if( is_string( $source ) ) {
1981 $this->addWikiMsg( 'viewsourcetext' );
1984 'id' => 'wpTextbox1',
1985 'name' => 'wpTextbox1',
1986 'cols' => $wgUser->getOption( 'cols' ),
1987 'rows' => $wgUser->getOption( 'rows' ),
1988 'readonly' => 'readonly'
1990 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1992 // Show templates used by this article
1993 $skin = $wgUser->getSkin();
1994 $article = new Article( $this->getTitle() );
1995 $this->addHTML( "<div class='templatesUsed'>
1996 {$skin->formatTemplates( $article->getUsedTemplates() )}
2001 # If the title doesn't exist, it's fairly pointless to print a return
2002 # link to it. After all, you just tried editing it and couldn't, so
2003 # what's there to do there?
2004 if( $this->getTitle()->exists() ) {
2005 $this->returnToMain( null, $this->getTitle() );
2010 * Adds JS-based password security checker
2011 * @param $passwordId String ID of input box containing password
2012 * @param $retypeId String ID of input box containing retyped password
2015 public function addPasswordSecurity( $passwordId, $retypeId ) {
2017 'password' => '#' . $passwordId,
2018 'retype' => '#' . $retypeId,
2019 'messages' => array(),
2021 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2022 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2024 $data['messages'][$message] = wfMsg( $message );
2026 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2027 $this->addModules( 'mediawiki.legacy.password' );
2030 public function showFatalError( $message ) {
2031 $this->setPageTitle( wfMsg( 'internalerror' ) );
2032 $this->setRobotPolicy( 'noindex,nofollow' );
2033 $this->setArticleRelated( false );
2034 $this->enableClientCache( false );
2035 $this->mRedirect
= '';
2036 $this->mBodytext
= $message;
2039 public function showUnexpectedValueError( $name, $val ) {
2040 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2043 public function showFileCopyError( $old, $new ) {
2044 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2047 public function showFileRenameError( $old, $new ) {
2048 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2051 public function showFileDeleteError( $name ) {
2052 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2055 public function showFileNotFoundError( $name ) {
2056 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2060 * Add a "return to" link pointing to a specified title
2062 * @param $title Title to link
2063 * @param $query String: query string
2064 * @param $text String text of the link (input is not escaped)
2066 public function addReturnTo( $title, $query = array(), $text = null ) {
2068 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2071 $wgUser->getSkin()->link( $title, $text, array(), $query )
2073 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2077 * Add a "return to" link pointing to a specified title,
2078 * or the title indicated in the request, or else the main page
2080 * @param $unused No longer used
2081 * @param $returnto Title or String to return to
2082 * @param $returntoquery String: query string for the return to link
2084 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2087 if ( $returnto == null ) {
2088 $returnto = $wgRequest->getText( 'returnto' );
2091 if ( $returntoquery == null ) {
2092 $returntoquery = $wgRequest->getText( 'returntoquery' );
2095 if ( $returnto === '' ) {
2096 $returnto = Title
::newMainPage();
2099 if ( is_object( $returnto ) ) {
2100 $titleObj = $returnto;
2102 $titleObj = Title
::newFromText( $returnto );
2104 if ( !is_object( $titleObj ) ) {
2105 $titleObj = Title
::newMainPage();
2108 $this->addReturnTo( $titleObj, $returntoquery );
2112 * @param $sk Skin The given Skin
2113 * @param $includeStyle Boolean: unused
2114 * @return String: The doctype, opening <html>, and head element.
2116 public function headElement( Skin
$sk, $includeStyle = true ) {
2117 global $wgOutputEncoding, $wgMimeType;
2118 global $wgUseTrackbacks, $wgHtml5;
2119 global $wgUser, $wgRequest, $wgLang;
2121 if ( $sk->commonPrintStylesheet() ) {
2122 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2124 $sk->setupUserCss( $this );
2126 $ret = Html
::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2128 if ( $this->getHTMLTitle() == '' ) {
2129 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2132 $openHead = Html
::openElement( 'head' );
2134 # Don't bother with the newline if $head == ''
2135 $ret .= "$openHead\n";
2139 # More succinct than <meta http-equiv=Content-Type>, has the
2141 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2143 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2146 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2148 $ret .= implode( "\n", array(
2149 $this->getHeadLinks( $sk ),
2150 $this->buildCssLinks( $sk ),
2151 $this->getHeadItems()
2154 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2155 $ret .= $this->getTitle()->trackbackRDF();
2158 $closeHead = Html
::closeElement( 'head' );
2160 $ret .= "$closeHead\n";
2163 $bodyAttrs = array();
2165 # Crazy edit-on-double-click stuff
2166 $action = $wgRequest->getVal( 'action', 'view' );
2169 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2170 !in_array( $action, array( 'edit', 'submit' ) ) &&
2171 $wgUser->getOption( 'editondblclick' )
2174 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2178 $dir = wfUILang()->getDir();
2179 $bodyAttrs['class'] = "mediawiki $dir";
2181 if ( $wgLang->capitalizeAllNouns() ) {
2182 # A <body> class is probably not the best way to do this . . .
2183 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2185 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2186 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
2187 $bodyAttrs['class'] .= ' ns-special';
2188 } elseif ( $this->getTitle()->isTalkPage() ) {
2189 $bodyAttrs['class'] .= ' ns-talk';
2191 $bodyAttrs['class'] .= ' ns-subject';
2193 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2194 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
2196 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2197 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2199 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2205 * Get a ResourceLoader object associated with this OutputPage
2207 public function getResourceLoader() {
2208 if ( is_null( $this->mResourceLoader
) ) {
2209 $this->mResourceLoader
= new ResourceLoader();
2211 return $this->mResourceLoader
;
2217 * @param $modules Array/string with the module name
2218 * @param $only string May be styles, messages or scripts
2219 * @param $useESI boolean
2220 * @return string html <script> and <style> tags
2222 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2223 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2224 $wgResourceLoaderInlinePrivateModules;
2225 // Lazy-load ResourceLoader
2226 // TODO: Should this be a static function of ResourceLoader instead?
2227 // TODO: Divide off modules starting with "user", and add the user parameter to them
2229 'lang' => $wgLang->getCode(),
2230 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2231 'skin' => $skin->getSkinName(),
2235 if ( !count( $modules ) ) {
2239 if ( count( $modules ) > 1 ) {
2240 // Remove duplicate module requests
2241 $modules = array_unique( (array) $modules );
2242 // Sort module names so requests are more uniform
2245 if ( ResourceLoader
::inDebugMode() ) {
2246 // Recursively call us for every item
2248 foreach ( $modules as $name ) {
2249 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2255 // Create keyed-by-group list of module objects from modules list
2257 $resourceLoader = $this->getResourceLoader();
2258 foreach ( (array) $modules as $name ) {
2259 $module = $resourceLoader->getModule( $name );
2260 $group = $module->getGroup();
2261 if ( !isset( $groups[$group] ) ) {
2262 $groups[$group] = array();
2264 $groups[$group][$name] = $module;
2267 foreach ( $groups as $group => $modules ) {
2268 $query['modules'] = implode( '|', array_keys( $modules ) );
2269 // Special handling for user-specific groups
2270 if ( ( $group === 'user' ||
$group === 'private' ) && $wgUser->isLoggedIn() ) {
2271 $query['user'] = $wgUser->getName();
2273 // Support inlining of private modules if configured as such
2274 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2275 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2276 if ( $only == 'styles' ) {
2277 $links .= Html
::inlineStyle(
2278 $resourceLoader->makeModuleResponse( $context, $modules )
2281 $links .= Html
::inlineScript(
2282 ResourceLoader
::makeLoaderConditionalScript(
2283 $resourceLoader->makeModuleResponse( $context, $modules )
2289 // Special handling for user and site groups; because users might change their stuff
2290 // on-wiki like site or user pages, or user preferences; we need to find the highest
2291 // timestamp of these user-changable modules so we can ensure cache misses on change
2292 if ( $group === 'user' ||
$group === 'site' ) {
2293 // Create a fake request based on the one we are about to make so modules return
2295 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2296 // Get the maximum timestamp
2298 foreach ( $modules as $module ) {
2299 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2301 // Add a version parameter so cache will break when things change
2302 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, round( $timestamp, -2 ) );
2304 // Make queries uniform in order
2307 $url = wfAppendQuery( $wgLoadScript, $query );
2308 if ( $useESI && $wgResourceLoaderUseESI ) {
2309 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2310 if ( $only == 'styles' ) {
2311 $links .= Html
::inlineStyle( $esi );
2313 $links .= Html
::inlineScript( $esi );
2316 // Automatically select style/script elements
2317 if ( $only === 'styles' ) {
2318 $links .= Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2320 $links .= Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2328 * Gets the global variables and mScripts; also adds userjs to the end if
2329 * enabled. Despite the name, these scripts are no longer put in the
2330 * <head> but at the bottom of the <body>
2332 * @param $sk Skin object to use
2333 * @return String: HTML fragment
2335 function getHeadScripts( Skin
$sk ) {
2336 global $wgUser, $wgRequest, $wgUseSiteJs;
2338 // Startup - this will immediately load jquery and mediawiki modules
2339 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2341 // Configuration -- This could be merged together with the load and go, but
2342 // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
2343 $scripts .= Skin
::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2345 // Script and Messages "only" requests
2346 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2347 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2349 // Modules requests - let the client calculate dependencies and batch requests as it likes
2350 if ( $this->getModules() ) {
2351 $scripts .= Html
::inlineScript(
2352 ResourceLoader
::makeLoaderConditionalScript(
2353 Xml
::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
2354 Xml
::encodeJsCall( 'mediaWiki.loader.go', array() )
2360 $scripts .= "\n" . $this->mScripts
;
2362 // Add site JS if enabled
2363 if ( $wgUseSiteJs ) {
2364 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
2367 // Add user JS if enabled - trying to load user.options as a bundle if possible
2368 $userOptionsAdded = false;
2369 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2370 $action = $wgRequest->getVal( 'action', 'view' );
2371 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2372 # XXX: additional security check/prompt?
2373 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2375 $scripts .= $this->makeResourceLoaderLink(
2376 $sk, array( 'user', 'user.options' ), 'scripts'
2378 $userOptionsAdded = true;
2381 if ( !$userOptionsAdded ) {
2382 $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2389 * Add default \<meta\> tags
2391 protected function addDefaultMeta() {
2392 global $wgVersion, $wgHtml5;
2394 static $called = false;
2396 # Don't run this twice
2402 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2404 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2406 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2407 if( $p !== 'index,follow' ) {
2408 // http://www.robotstxt.org/wc/meta-user.html
2409 // Only show if it's different from the default robots policy
2410 $this->addMeta( 'robots', $p );
2413 if ( count( $this->mKeywords
) > 0 ) {
2415 "/<.*?" . ">/" => '',
2421 array_keys( $strip ),
2422 array_values( $strip ),
2423 implode( ',', $this->mKeywords
)
2430 * @return string HTML tag links to be put in the header.
2432 public function getHeadLinks( Skin
$sk ) {
2435 // Ideally this should happen earlier, somewhere. :P
2436 $this->addDefaultMeta();
2440 foreach ( $this->mMetatags
as $tag ) {
2441 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2443 $tag[0] = substr( $tag[0], 5 );
2447 $tags[] = Html
::element( 'meta',
2450 'content' => $tag[1]
2454 foreach ( $this->mLinktags
as $tag ) {
2455 $tags[] = Html
::element( 'link', $tag );
2459 foreach( $this->getSyndicationLinks() as $format => $link ) {
2460 # Use the page name for the title (accessed through $wgTitle since
2461 # there's no other way). In principle, this could lead to issues
2462 # with having the same name for different feeds corresponding to
2463 # the same page, but we can't avoid that at this low a level.
2465 $tags[] = $this->feedLink(
2468 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2469 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2473 # Recent changes feed should appear on every page (except recentchanges,
2474 # that would be redundant). Put it after the per-page feed to avoid
2475 # changing existing behavior. It's still available, probably via a
2476 # menu in your browser. Some sites might have a different feed they'd
2477 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2478 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2479 # If so, use it instead.
2481 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2482 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2484 if ( $wgOverrideSiteFeed ) {
2485 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2486 $tags[] = $this->feedLink(
2488 htmlspecialchars( $feedUrl ),
2489 wfMsg( "site-{$type}-feed", $wgSitename )
2492 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2493 foreach ( $wgAdvertisedFeedTypes as $format ) {
2494 $tags[] = $this->feedLink(
2496 $rctitle->getLocalURL( "feed={$format}" ),
2497 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2502 return implode( "\n", $tags );
2506 * Generate a <link rel/> for a feed.
2508 * @param $type String: feed type
2509 * @param $url String: URL to the feed
2510 * @param $text String: value of the "title" attribute
2511 * @return String: HTML fragment
2513 private function feedLink( $type, $url, $text ) {
2514 return Html
::element( 'link', array(
2515 'rel' => 'alternate',
2516 'type' => "application/$type+xml",
2523 * Add a local or specified stylesheet, with the given media options.
2524 * Meant primarily for internal use...
2526 * @param $style String: URL to the file
2527 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2528 * @param $condition String: for IE conditional comments, specifying an IE version
2529 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2531 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2533 // Even though we expect the media type to be lowercase, but here we
2534 // force it to lowercase to be safe.
2536 $options['media'] = $media;
2539 $options['condition'] = $condition;
2542 $options['dir'] = $dir;
2544 $this->styles
[$style] = $options;
2548 * Adds inline CSS styles
2549 * @param $style_css Mixed: inline CSS
2551 public function addInlineStyle( $style_css ){
2552 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2556 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2557 * These will be applied to various media & IE conditionals.
2558 * @param $sk Skin object
2560 public function buildCssLinks( $sk ) {
2562 // Add ResourceLoader styles
2563 // Split the styles into three groups
2564 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2565 $resourceLoader = $this->getResourceLoader();
2566 foreach ( $this->getModuleStyles() as $name ) {
2567 $group = $resourceLoader->getModule( $name )->getGroup();
2568 // Modules in groups named "other" or anything different than "user" or "site" will
2569 // be placed in the "other" group
2570 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2573 // We want site and user styles to override dynamically added styles from modules, but we want
2574 // dynamically added styles to override statically added styles from other modules. So the order
2575 // has to be other, dynamic, site, user
2576 // Add statically added styles for other modules
2577 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2578 // Add normal styles added through addStyle()/addInlineStyle() here
2579 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2580 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2581 // We use a <meta> tag with a made-up name for this because that's valid HTML
2582 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2583 // Add site and user styles
2584 $ret .= $this->makeResourceLoaderLink(
2585 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2590 public function buildCssLinksArray() {
2592 foreach( $this->styles
as $file => $options ) {
2593 $link = $this->styleLink( $file, $options );
2595 $links[$file] = $link;
2602 * Generate \<link\> tags for stylesheets
2604 * @param $style String: URL to the file
2605 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2607 * @return String: HTML fragment
2609 protected function styleLink( $style, $options ) {
2610 if( isset( $options['dir'] ) ) {
2611 $siteDir = wfUILang()->getDir();
2612 if( $siteDir != $options['dir'] ) {
2617 if( isset( $options['media'] ) ) {
2618 $media = $this->transformCssMedia( $options['media'] );
2619 if( is_null( $media ) ) {
2626 if( substr( $style, 0, 1 ) == '/' ||
2627 substr( $style, 0, 5 ) == 'http:' ||
2628 substr( $style, 0, 6 ) == 'https:' ) {
2631 global $wgStylePath, $wgStyleVersion;
2632 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2635 $link = Html
::linkedStyle( $url, $media );
2637 if( isset( $options['condition'] ) ) {
2638 $condition = htmlspecialchars( $options['condition'] );
2639 $link = "<!--[if $condition]>$link<![endif]-->";
2645 * Transform "media" attribute based on request parameters
2647 * @param $media String: current value of the "media" attribute
2648 * @return String: modified value of the "media" attribute
2650 function transformCssMedia( $media ) {
2651 global $wgRequest, $wgHandheldForIPhone;
2653 // Switch in on-screen display for media testing
2655 'printable' => 'print',
2656 'handheld' => 'handheld',
2658 foreach( $switches as $switch => $targetMedia ) {
2659 if( $wgRequest->getBool( $switch ) ) {
2660 if( $media == $targetMedia ) {
2662 } elseif( $media == 'screen' ) {
2668 // Expand longer media queries as iPhone doesn't grok 'handheld'
2669 if( $wgHandheldForIPhone ) {
2670 $mediaAliases = array(
2671 'screen' => 'screen and (min-device-width: 481px)',
2672 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2675 if( isset( $mediaAliases[$media] ) ) {
2676 $media = $mediaAliases[$media];
2684 * Turn off regular page output and return an error reponse
2685 * for when rate limiting has triggered.
2687 public function rateLimited() {
2688 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2689 $this->setRobotPolicy( 'noindex,follow' );
2690 $this->setArticleRelated( false );
2691 $this->enableClientCache( false );
2692 $this->mRedirect
= '';
2694 $this->setStatusCode( 503 );
2695 $this->addWikiMsg( 'actionthrottledtext' );
2697 $this->returnToMain( null, $this->getTitle() );
2701 * Show a warning about slave lag
2703 * If the lag is higher than $wgSlaveLagCritical seconds,
2704 * then the warning is a bit more obvious. If the lag is
2705 * lower than $wgSlaveLagWarning, then no warning is shown.
2707 * @param $lag Integer: slave lag
2709 public function showLagWarning( $lag ) {
2710 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2711 if( $lag >= $wgSlaveLagWarning ) {
2712 $message = $lag < $wgSlaveLagCritical
2715 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2716 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2721 * Add a wikitext-formatted message to the output.
2722 * This is equivalent to:
2724 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2726 public function addWikiMsg( /*...*/ ) {
2727 $args = func_get_args();
2728 $name = array_shift( $args );
2729 $this->addWikiMsgArray( $name, $args );
2733 * Add a wikitext-formatted message to the output.
2734 * Like addWikiMsg() except the parameters are taken as an array
2735 * instead of a variable argument list.
2737 * $options is passed through to wfMsgExt(), see that function for details.
2739 public function addWikiMsgArray( $name, $args, $options = array() ) {
2740 $options[] = 'parse';
2741 $text = wfMsgExt( $name, $options, $args );
2742 $this->addHTML( $text );
2746 * This function takes a number of message/argument specifications, wraps them in
2747 * some overall structure, and then parses the result and adds it to the output.
2749 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2750 * on. The subsequent arguments may either be strings, in which case they are the
2751 * message names, or arrays, in which case the first element is the message name,
2752 * and subsequent elements are the parameters to that message.
2754 * The special named parameter 'options' in a message specification array is passed
2755 * through to the $options parameter of wfMsgExt().
2757 * Don't use this for messages that are not in users interface language.
2761 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2765 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2767 * The newline after opening div is needed in some wikitext. See bug 19226.
2769 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2770 $msgSpecs = func_get_args();
2771 array_shift( $msgSpecs );
2772 $msgSpecs = array_values( $msgSpecs );
2774 foreach ( $msgSpecs as $n => $spec ) {
2776 if ( is_array( $spec ) ) {
2778 $name = array_shift( $args );
2779 if ( isset( $args['options'] ) ) {
2780 $options = $args['options'];
2781 unset( $args['options'] );
2787 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2789 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2793 * Include jQuery core. Use this to avoid loading it multiple times
2794 * before we get a usable script loader.
2796 * @param $modules Array: list of jQuery modules which should be loaded
2797 * @return Array: the list of modules which were not loaded.
2799 * @deprecated @since 1.17
2801 public function includeJQuery( $modules = array() ) {