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 array_values( array_unique( $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 array_values( array_unique( $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 array_values( array_unique( $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 array_values( array_unique( $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 * @deprecated use parserOptions() instead
1006 public function setParserOptions( $options ) {
1007 wfDeprecated( __METHOD__ );
1008 return $this->parserOptions( $options );
1012 * Get/set the ParserOptions object to use for wikitext parsing
1014 * @param $options either the ParserOption to use or null to only get the
1015 * current ParserOption object
1016 * @return current ParserOption object
1018 public function parserOptions( $options = null ) {
1019 if ( !$this->mParserOptions ) {
1020 $this->mParserOptions = new ParserOptions;
1022 return wfSetVar( $this->mParserOptions, $options );
1026 * Set the revision ID which will be seen by the wiki text parser
1027 * for things such as embedded {{REVISIONID}} variable use.
1029 * @param $revid Mixed: an positive integer, or null
1030 * @return Mixed: previous value
1032 public function setRevisionId( $revid ) {
1033 $val = is_null( $revid ) ? null : intval( $revid );
1034 return wfSetVar( $this->mRevisionId, $val );
1038 * Get the current revision ID
1042 public function getRevisionId() {
1043 return $this->mRevisionId;
1047 * Convert wikitext to HTML and add it to the buffer
1048 * Default assumes that the current page title will be used.
1050 * @param $text String
1051 * @param $linestart Boolean: is this the start of a line?
1053 public function addWikiText( $text, $linestart = true ) {
1054 $title = $this->getTitle(); // Work arround E_STRICT
1055 $this->addWikiTextTitle( $text, $title, $linestart );
1059 * Add wikitext with a custom Title object
1061 * @param $text String: wikitext
1062 * @param $title Title object
1063 * @param $linestart Boolean: is this the start of a line?
1065 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1066 $this->addWikiTextTitle( $text, $title, $linestart );
1070 * Add wikitext with a custom Title object and
1072 * @param $text String: wikitext
1073 * @param $title Title object
1074 * @param $linestart Boolean: is this the start of a line?
1076 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1077 $this->addWikiTextTitle( $text, $title, $linestart, true );
1081 * Add wikitext with tidy enabled
1083 * @param $text String: wikitext
1084 * @param $linestart Boolean: is this the start of a line?
1086 public function addWikiTextTidy( $text, $linestart = true ) {
1087 $title = $this->getTitle();
1088 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1092 * Add wikitext with a custom Title object
1094 * @param $text String: wikitext
1095 * @param $title Title object
1096 * @param $linestart Boolean: is this the start of a line?
1097 * @param $tidy Boolean: whether to use tidy
1099 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1102 wfProfileIn( __METHOD__ );
1104 wfIncrStats( 'pcache_not_possible' );
1106 $popts = $this->parserOptions();
1107 $oldTidy = $popts->setTidy( $tidy );
1109 $parserOutput = $wgParser->parse(
1110 $text, $title, $popts,
1111 $linestart, true, $this->mRevisionId
1114 $popts->setTidy( $oldTidy );
1116 $this->addParserOutput( $parserOutput );
1118 wfProfileOut( __METHOD__ );
1122 * Add wikitext to the buffer, assuming that this is the primary text for a page view
1123 * Saves the text into the parser cache if possible.
1125 * @param $text String: wikitext
1126 * @param $article Article object
1127 * @param $cache Boolean
1128 * @deprecated Use Article::outputWikitext
1130 public function addPrimaryWikiText( $text, $article, $cache = true ) {
1133 wfDeprecated( __METHOD__ );
1135 $popts = $this->parserOptions();
1136 $popts->setTidy( true );
1137 $parserOutput = $wgParser->parse(
1138 $text, $article->mTitle,
1139 $popts, true, true, $this->mRevisionId
1141 $popts->setTidy( false );
1142 if ( $cache && $article && $parserOutput->isCacheable() ) {
1143 $parserCache = ParserCache::singleton();
1144 $parserCache->save( $parserOutput, $article, $popts );
1147 $this->addParserOutput( $parserOutput );
1151 * @deprecated use addWikiTextTidy()
1153 public function addSecondaryWikiText( $text, $linestart = true ) {
1154 wfDeprecated( __METHOD__ );
1155 $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
1159 * Add a ParserOutput object, but without Html
1161 * @param $parserOutput ParserOutput object
1163 public function addParserOutputNoText( &$parserOutput ) {
1164 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1165 $this->addCategoryLinks( $parserOutput->getCategories() );
1166 $this->mNewSectionLink = $parserOutput->getNewSection();
1167 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1169 $this->mParseWarnings = $parserOutput->getWarnings();
1170 if ( !$parserOutput->isCacheable() ) {
1171 $this->enableClientCache( false );
1173 $this->mNoGallery = $parserOutput->getNoGallery();
1174 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1175 $this->addModules( $parserOutput->getModules() );
1177 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1178 if ( isset( $this->mTemplateIds[$ns] ) ) {
1179 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1181 $this->mTemplateIds[$ns] = $dbks;
1185 // Hooks registered in the object
1186 global $wgParserOutputHooks;
1187 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1188 list( $hookName, $data ) = $hookInfo;
1189 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1190 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1194 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1198 * Add a ParserOutput object
1200 * @param $parserOutput ParserOutput
1202 function addParserOutput( &$parserOutput ) {
1203 $this->addParserOutputNoText( $parserOutput );
1204 $text = $parserOutput->getText();
1205 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1206 $this->addHTML( $text );
1211 * Add the output of a QuickTemplate to the output buffer
1213 * @param $template QuickTemplate
1215 public function addTemplate( &$template ) {
1217 $template->execute();
1218 $this->addHTML( ob_get_contents() );
1223 * Parse wikitext and return the HTML.
1225 * @param $text String
1226 * @param $linestart Boolean: is this the start of a line?
1227 * @param $interface Boolean: use interface language ($wgLang instead of
1228 * $wgContLang) while parsing language sensitive magic
1229 * words like GRAMMAR and PLURAL
1230 * @return String: HTML
1232 public function parse( $text, $linestart = true, $interface = false ) {
1234 if( is_null( $this->getTitle() ) ) {
1235 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1237 $popts = $this->parserOptions();
1239 $popts->setInterfaceMessage( true );
1241 $parserOutput = $wgParser->parse(
1242 $text, $this->getTitle(), $popts,
1243 $linestart, true, $this->mRevisionId
1246 $popts->setInterfaceMessage( false );
1248 return $parserOutput->getText();
1252 * Parse wikitext, strip paragraphs, and return the HTML.
1254 * @param $text String
1255 * @param $linestart Boolean: is this the start of a line?
1256 * @param $interface Boolean: use interface language ($wgLang instead of
1257 * $wgContLang) while parsing language sensitive magic
1258 * words like GRAMMAR and PLURAL
1259 * @return String: HTML
1261 public function parseInline( $text, $linestart = true, $interface = false ) {
1262 $parsed = $this->parse( $text, $linestart, $interface );
1265 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1275 * @param $article Article
1276 * @return Boolean: true if successful, else false.
1278 public function tryParserCache( &$article ) {
1279 wfDeprecated( __METHOD__ );
1280 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
1282 if ( $parserOutput !== false ) {
1283 $this->addParserOutput( $parserOutput );
1291 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1293 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1295 public function setSquidMaxage( $maxage ) {
1296 $this->mSquidMaxage = $maxage;
1300 * Use enableClientCache(false) to force it to send nocache headers
1304 public function enableClientCache( $state ) {
1305 return wfSetVar( $this->mEnableClientCache, $state );
1309 * Get the list of cookies that will influence on the cache
1313 function getCacheVaryCookies() {
1314 global $wgCookiePrefix, $wgCacheVaryCookies;
1316 if ( $cookies === null ) {
1317 $cookies = array_merge(
1319 "{$wgCookiePrefix}Token",
1320 "{$wgCookiePrefix}LoggedOut",
1325 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1331 * Return whether this page is not cacheable because "useskin" or "uselang"
1332 * URL parameters were passed.
1336 function uncacheableBecauseRequestVars() {
1338 return $wgRequest->getText( 'useskin', false ) === false
1339 && $wgRequest->getText( 'uselang', false ) === false;
1343 * Check if the request has a cache-varying cookie header
1344 * If it does, it's very important that we don't allow public caching
1348 function haveCacheVaryCookies() {
1350 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1351 if ( $cookieHeader === false ) {
1354 $cvCookies = $this->getCacheVaryCookies();
1355 foreach ( $cvCookies as $cookieName ) {
1356 # Check for a simple string match, like the way squid does it
1357 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1358 wfDebug( __METHOD__ . ": found $cookieName\n" );
1362 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1367 * Add an HTTP header that will influence on the cache
1369 * @param $header String: header name
1370 * @param $option either an Array or null
1371 * @fixme Document the $option parameter; it appears to be for
1372 * X-Vary-Options but what format is acceptable?
1374 public function addVaryHeader( $header, $option = null ) {
1375 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1376 $this->mVaryHeader[$header] = (array)$option;
1377 } elseif( is_array( $option ) ) {
1378 if( is_array( $this->mVaryHeader[$header] ) ) {
1379 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1381 $this->mVaryHeader[$header] = $option;
1384 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1388 * Get a complete X-Vary-Options header
1392 public function getXVO() {
1393 $cvCookies = $this->getCacheVaryCookies();
1395 $cookiesOption = array();
1396 foreach ( $cvCookies as $cookieName ) {
1397 $cookiesOption[] = 'string-contains=' . $cookieName;
1399 $this->addVaryHeader( 'Cookie', $cookiesOption );
1402 foreach( $this->mVaryHeader as $header => $option ) {
1403 $newheader = $header;
1404 if( is_array( $option ) ) {
1405 $newheader .= ';' . implode( ';', $option );
1407 $headers[] = $newheader;
1409 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1415 * bug 21672: Add Accept-Language to Vary and XVO headers
1416 * if there's no 'variant' parameter existed in GET.
1419 * /w/index.php?title=Main_page should always be served; but
1420 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1422 function addAcceptLanguage() {
1423 global $wgRequest, $wgContLang;
1424 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1425 $variants = $wgContLang->getVariants();
1426 $aloption = array();
1427 foreach ( $variants as $variant ) {
1428 if( $variant === $wgContLang->getCode() ) {
1431 $aloption[] = 'string-contains=' . $variant;
1433 // IE and some other browsers use another form of language code
1434 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1435 // We should handle these too.
1436 $ievariant = explode( '-', $variant );
1437 if ( count( $ievariant ) == 2 ) {
1438 $ievariant[1] = strtoupper( $ievariant[1] );
1439 $ievariant = implode( '-', $ievariant );
1440 $aloption[] = 'string-contains=' . $ievariant;
1444 $this->addVaryHeader( 'Accept-Language', $aloption );
1449 * Set a flag which will cause an X-Frame-Options header appropriate for
1450 * edit pages to be sent. The header value is controlled by
1451 * $wgEditPageFrameOptions.
1453 * This is the default for special pages. If you display a CSRF-protected
1454 * form on an ordinary view page, then you need to call this function.
1456 public function preventClickjacking( $enable = true ) {
1457 $this->mPreventClickjacking = $enable;
1461 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1462 * This can be called from pages which do not contain any CSRF-protected
1465 public function allowClickjacking() {
1466 $this->mPreventClickjacking = false;
1470 * Get the X-Frame-Options header value (without the name part), or false
1471 * if there isn't one. This is used by Skin to determine whether to enable
1472 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1474 public function getFrameOptions() {
1475 global $wgBreakFrames, $wgEditPageFrameOptions;
1476 if ( $wgBreakFrames ) {
1478 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1479 return $wgEditPageFrameOptions;
1484 * Send cache control HTTP headers
1486 public function sendCacheControl() {
1487 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1489 $response = $wgRequest->response();
1490 if ( $wgUseETag && $this->mETag ) {
1491 $response->header( "ETag: $this->mETag" );
1494 $this->addAcceptLanguage();
1496 # don't serve compressed data to clients who can't handle it
1497 # maintain different caches for logged-in users and non-logged in ones
1498 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1501 # Add an X-Vary-Options header for Squid with Wikimedia patches
1502 $response->header( $this->getXVO() );
1505 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1507 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1508 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1512 # We'll purge the proxy cache explicitly, but require end user agents
1513 # to revalidate against the proxy on each visit.
1514 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1515 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1516 # start with a shorter timeout for initial testing
1517 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1518 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1519 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1521 # We'll purge the proxy cache for anons explicitly, but require end user agents
1522 # to revalidate against the proxy on each visit.
1523 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1524 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1525 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1526 # start with a shorter timeout for initial testing
1527 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1528 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1531 # We do want clients to cache if they can, but they *must* check for updates
1532 # on revisiting the page.
1533 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1534 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1535 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1537 if($this->mLastModified) {
1538 $response->header( "Last-Modified: {$this->mLastModified}" );
1541 wfDebug( __METHOD__ . ": no caching **\n", false );
1543 # In general, the absence of a last modified header should be enough to prevent
1544 # the client from using its cache. We send a few other things just to make sure.
1545 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1546 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1547 $response->header( 'Pragma: no-cache' );
1552 * Get the message associed with the HTTP response code $code
1554 * @param $code Integer: status code
1555 * @return String or null: message or null if $code is not in the list of
1558 public static function getStatusMessage( $code ) {
1559 static $statusMessage = array(
1561 101 => 'Switching Protocols',
1562 102 => 'Processing',
1566 203 => 'Non-Authoritative Information',
1567 204 => 'No Content',
1568 205 => 'Reset Content',
1569 206 => 'Partial Content',
1570 207 => 'Multi-Status',
1571 300 => 'Multiple Choices',
1572 301 => 'Moved Permanently',
1575 304 => 'Not Modified',
1577 307 => 'Temporary Redirect',
1578 400 => 'Bad Request',
1579 401 => 'Unauthorized',
1580 402 => 'Payment Required',
1583 405 => 'Method Not Allowed',
1584 406 => 'Not Acceptable',
1585 407 => 'Proxy Authentication Required',
1586 408 => 'Request Timeout',
1589 411 => 'Length Required',
1590 412 => 'Precondition Failed',
1591 413 => 'Request Entity Too Large',
1592 414 => 'Request-URI Too Large',
1593 415 => 'Unsupported Media Type',
1594 416 => 'Request Range Not Satisfiable',
1595 417 => 'Expectation Failed',
1596 422 => 'Unprocessable Entity',
1598 424 => 'Failed Dependency',
1599 500 => 'Internal Server Error',
1600 501 => 'Not Implemented',
1601 502 => 'Bad Gateway',
1602 503 => 'Service Unavailable',
1603 504 => 'Gateway Timeout',
1604 505 => 'HTTP Version Not Supported',
1605 507 => 'Insufficient Storage'
1607 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1611 * Finally, all the text has been munged and accumulated into
1612 * the object, let's actually output it:
1614 public function output() {
1615 global $wgUser, $wgOutputEncoding, $wgRequest;
1616 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1617 global $wgUseAjax, $wgAjaxWatch;
1618 global $wgEnableMWSuggest, $wgUniversalEditButton;
1621 if( $this->mDoNothing ) {
1624 wfProfileIn( __METHOD__ );
1625 if ( $this->mRedirect != '' ) {
1626 # Standards require redirect URLs to be absolute
1627 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1628 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1629 if( !$wgDebugRedirects ) {
1630 $message = self::getStatusMessage( $this->mRedirectCode );
1631 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1633 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1635 $this->sendCacheControl();
1637 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1638 if( $wgDebugRedirects ) {
1639 $url = htmlspecialchars( $this->mRedirect );
1640 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1641 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1642 print "</body>\n</html>\n";
1644 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1646 wfProfileOut( __METHOD__ );
1648 } elseif ( $this->mStatusCode ) {
1649 $message = self::getStatusMessage( $this->mStatusCode );
1651 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1655 $sk = $wgUser->getSkin();
1657 // Add base resources
1658 $this->addModules( 'mediawiki.util' );
1659 global $wgIncludeLegacyJavaScript;
1660 if( $wgIncludeLegacyJavaScript ){
1661 $this->addModules( 'mediawiki.legacy.wikibits' );
1664 // Add various resources if required
1666 $this->addModules( 'mediawiki.legacy.ajax' );
1668 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1670 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1671 $this->addModules( 'mediawiki.legacy.ajaxwatch' );
1674 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1675 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1679 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1680 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1683 if( $wgUniversalEditButton ) {
1684 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1685 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1686 // Original UniversalEditButton
1687 $msg = wfMsg( 'edit' );
1688 $this->addLink( array(
1689 'rel' => 'alternate',
1690 'type' => 'application/x-wiki',
1692 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1694 // Alternate edit link
1695 $this->addLink( array(
1698 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1704 # Buffer output; final headers may depend on later processing
1707 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1708 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1710 // Prevent framing, if requested
1711 $frameOptions = $this->getFrameOptions();
1712 if ( $frameOptions ) {
1713 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1716 if ( $this->mArticleBodyOnly ) {
1717 $this->out( $this->mBodytext );
1719 // Hook that allows last minute changes to the output page, e.g.
1720 // adding of CSS or Javascript by extensions.
1721 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1723 wfProfileIn( 'Output-skin' );
1724 $sk->outputPage( $this );
1725 wfProfileOut( 'Output-skin' );
1728 $this->sendCacheControl();
1730 wfProfileOut( __METHOD__ );
1734 * Actually output something with print(). Performs an iconv to the
1735 * output encoding, if needed.
1737 * @param $ins String: the string to output
1739 public function out( $ins ) {
1740 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1741 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1744 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1745 if ( false === $outs ) {
1755 public static function setEncodings() {
1756 global $wgInputEncoding, $wgOutputEncoding;
1758 $wgInputEncoding = strtolower( $wgInputEncoding );
1760 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1761 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1764 $wgOutputEncoding = $wgInputEncoding;
1768 * @deprecated use wfReportTime() instead.
1772 public function reportTime() {
1773 wfDeprecated( __METHOD__ );
1774 $time = wfReportTime();
1779 * Produce a "user is blocked" page.
1781 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1784 function blockedPage( $return = true ) {
1785 global $wgUser, $wgContLang, $wgLang;
1787 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1788 $this->setRobotPolicy( 'noindex,nofollow' );
1789 $this->setArticleRelated( false );
1791 $name = User::whoIs( $wgUser->blockedBy() );
1792 $reason = $wgUser->blockedFor();
1793 if( $reason == '' ) {
1794 $reason = wfMsg( 'blockednoreason' );
1796 $blockTimestamp = $wgLang->timeanddate(
1797 wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
1801 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1803 $blockid = $wgUser->mBlock->mId;
1805 $blockExpiry = $wgUser->mBlock->mExpiry;
1806 if ( $blockExpiry == 'infinity' ) {
1807 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1808 // Search for localization in 'ipboptions'
1809 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1810 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1811 if ( strpos( $option, ':' ) === false ) {
1814 list( $show, $value ) = explode( ':', $option );
1815 if ( $value == 'infinite' || $value == 'indefinite' ) {
1816 $blockExpiry = $show;
1821 $blockExpiry = $wgLang->timeanddate(
1822 wfTimestamp( TS_MW, $blockExpiry ),
1827 if ( $wgUser->mBlock->mAuto ) {
1828 $msg = 'autoblockedtext';
1830 $msg = 'blockedtext';
1833 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1834 * This could be a username, an IP range, or a single IP. */
1835 $intended = $wgUser->mBlock->mAddress;
1838 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1839 $intended, $blockTimestamp
1842 # Don't auto-return to special pages
1844 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1845 $this->returnToMain( null, $return );
1850 * Output a standard error page
1852 * @param $title String: message key for page title
1853 * @param $msg String: message key for page text
1854 * @param $params Array: message parameters
1856 public function showErrorPage( $title, $msg, $params = array() ) {
1857 if ( $this->getTitle() ) {
1858 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1860 $this->setPageTitle( wfMsg( $title ) );
1861 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1862 $this->setRobotPolicy( 'noindex,nofollow' );
1863 $this->setArticleRelated( false );
1864 $this->enableClientCache( false );
1865 $this->mRedirect = '';
1866 $this->mBodytext = '';
1868 array_unshift( $params, 'parse' );
1869 array_unshift( $params, $msg );
1870 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1872 $this->returnToMain();
1876 * Output a standard permission error page
1878 * @param $errors Array: error message keys
1879 * @param $action String: action that was denied or null if unknown
1881 public function showPermissionsErrorPage( $errors, $action = null ) {
1882 $this->mDebugtext .= 'Original title: ' .
1883 $this->getTitle()->getPrefixedText() . "\n";
1884 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1885 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1886 $this->setRobotPolicy( 'noindex,nofollow' );
1887 $this->setArticleRelated( false );
1888 $this->enableClientCache( false );
1889 $this->mRedirect = '';
1890 $this->mBodytext = '';
1891 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1895 * Display an error page indicating that a given version of MediaWiki is
1896 * required to use it
1898 * @param $version Mixed: the version of MediaWiki needed to use the page
1900 public function versionRequired( $version ) {
1901 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1902 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1903 $this->setRobotPolicy( 'noindex,nofollow' );
1904 $this->setArticleRelated( false );
1905 $this->mBodytext = '';
1907 $this->addWikiMsg( 'versionrequiredtext', $version );
1908 $this->returnToMain();
1912 * Display an error page noting that a given permission bit is required.
1914 * @param $permission String: key required
1916 public function permissionRequired( $permission ) {
1919 $this->setPageTitle( wfMsg( 'badaccess' ) );
1920 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1921 $this->setRobotPolicy( 'noindex,nofollow' );
1922 $this->setArticleRelated( false );
1923 $this->mBodytext = '';
1925 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1926 User::getGroupsWithPermission( $permission ) );
1930 $wgLang->commaList( $groups ),
1934 $this->addWikiMsg( 'badaccess-group0' );
1936 $this->returnToMain();
1940 * Produce the stock "please login to use the wiki" page
1942 public function loginToUse() {
1945 if( $wgUser->isLoggedIn() ) {
1946 $this->permissionRequired( 'read' );
1950 $skin = $wgUser->getSkin();
1952 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1953 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1954 $this->setRobotPolicy( 'noindex,nofollow' );
1955 $this->setArticleFlag( false );
1957 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1958 $loginLink = $skin->link(
1960 wfMsgHtml( 'loginreqlink' ),
1962 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1963 array( 'known', 'noclasses' )
1965 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1966 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1968 # Don't return to the main page if the user can't read it
1969 # otherwise we'll end up in a pointless loop
1970 $mainPage = Title::newMainPage();
1971 if( $mainPage->userCanRead() ) {
1972 $this->returnToMain( null, $mainPage );
1977 * Format a list of error messages
1979 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1980 * @param $action String: action that was denied or null if unknown
1981 * @return String: the wikitext error-messages, formatted into a list.
1983 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1984 if ( $action == null ) {
1985 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1987 $action_desc = wfMsgNoTrans( "action-$action" );
1988 $text = wfMsgNoTrans(
1989 'permissionserrorstext-withaction',
1995 if ( count( $errors ) > 1 ) {
1996 $text .= '<ul class="permissions-errors">' . "\n";
1998 foreach( $errors as $error ) {
2000 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2005 $text .= "<div class=\"permissions-errors\">\n" .
2006 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2014 * Display a page stating that the Wiki is in read-only mode,
2015 * and optionally show the source of the page that the user
2016 * was trying to edit. Should only be called (for this
2017 * purpose) after wfReadOnly() has returned true.
2019 * For historical reasons, this function is _also_ used to
2020 * show the error message when a user tries to edit a page
2021 * they are not allowed to edit. (Unless it's because they're
2022 * blocked, then we show blockedPage() instead.) In this
2023 * case, the second parameter should be set to true and a list
2024 * of reasons supplied as the third parameter.
2026 * @todo Needs to be split into multiple functions.
2028 * @param $source String: source code to show (or null).
2029 * @param $protected Boolean: is this a permissions error?
2030 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2031 * @param $action String: action that was denied or null if unknown
2033 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2035 $skin = $wgUser->getSkin();
2037 $this->setRobotPolicy( 'noindex,nofollow' );
2038 $this->setArticleRelated( false );
2040 // If no reason is given, just supply a default "I can't let you do
2041 // that, Dave" message. Should only occur if called by legacy code.
2042 if ( $protected && empty( $reasons ) ) {
2043 $reasons[] = array( 'badaccess-group0' );
2046 if ( !empty( $reasons ) ) {
2047 // Permissions error
2049 $this->setPageTitle( wfMsg( 'viewsource' ) );
2051 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2054 $this->setPageTitle( wfMsg( 'badaccess' ) );
2056 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2058 // Wiki is read only
2059 $this->setPageTitle( wfMsg( 'readonly' ) );
2060 $reason = wfReadOnlyReason();
2061 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2064 // Show source, if supplied
2065 if( is_string( $source ) ) {
2066 $this->addWikiMsg( 'viewsourcetext' );
2069 'id' => 'wpTextbox1',
2070 'name' => 'wpTextbox1',
2071 'cols' => $wgUser->getOption( 'cols' ),
2072 'rows' => $wgUser->getOption( 'rows' ),
2073 'readonly' => 'readonly'
2075 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2077 // Show templates used by this article
2078 $skin = $wgUser->getSkin();
2079 $article = new Article( $this->getTitle() );
2080 $this->addHTML( "<div class='templatesUsed'>
2081 {$skin->formatTemplates( $article->getUsedTemplates() )}
2086 # If the title doesn't exist, it's fairly pointless to print a return
2087 # link to it. After all, you just tried editing it and couldn't, so
2088 # what's there to do there?
2089 if( $this->getTitle()->exists() ) {
2090 $this->returnToMain( null, $this->getTitle() );
2095 public function errorpage( $title, $msg ) {
2096 wfDeprecated( __METHOD__ );
2097 throw new ErrorPageError( $title, $msg );
2101 public function databaseError( $fname, $sql, $error, $errno ) {
2102 throw new MWException( "OutputPage::databaseError is obsolete\n" );
2106 public function fatalError( $message ) {
2107 wfDeprecated( __METHOD__ );
2108 throw new FatalError( $message );
2112 public function unexpectedValueError( $name, $val ) {
2113 wfDeprecated( __METHOD__ );
2114 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
2118 public function fileCopyError( $old, $new ) {
2119 wfDeprecated( __METHOD__ );
2120 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
2124 public function fileRenameError( $old, $new ) {
2125 wfDeprecated( __METHOD__ );
2126 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
2130 public function fileDeleteError( $name ) {
2131 wfDeprecated( __METHOD__ );
2132 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
2136 public function fileNotFoundError( $name ) {
2137 wfDeprecated( __METHOD__ );
2138 throw new FatalError( wfMsg( 'filenotfound', $name ) );
2141 public function showFatalError( $message ) {
2142 $this->setPageTitle( wfMsg( 'internalerror' ) );
2143 $this->setRobotPolicy( 'noindex,nofollow' );
2144 $this->setArticleRelated( false );
2145 $this->enableClientCache( false );
2146 $this->mRedirect = '';
2147 $this->mBodytext = $message;
2150 public function showUnexpectedValueError( $name, $val ) {
2151 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2154 public function showFileCopyError( $old, $new ) {
2155 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2158 public function showFileRenameError( $old, $new ) {
2159 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2162 public function showFileDeleteError( $name ) {
2163 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2166 public function showFileNotFoundError( $name ) {
2167 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2171 * Add a "return to" link pointing to a specified title
2173 * @param $title Title to link
2174 * @param $query String: query string
2175 * @param $text String text of the link (input is not escaped)
2177 public function addReturnTo( $title, $query = array(), $text = null ) {
2179 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2182 $wgUser->getSkin()->link( $title, $text, array(), $query )
2184 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2188 * Add a "return to" link pointing to a specified title,
2189 * or the title indicated in the request, or else the main page
2191 * @param $unused No longer used
2192 * @param $returnto Title or String to return to
2193 * @param $returntoquery String: query string for the return to link
2195 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2198 if ( $returnto == null ) {
2199 $returnto = $wgRequest->getText( 'returnto' );
2202 if ( $returntoquery == null ) {
2203 $returntoquery = $wgRequest->getText( 'returntoquery' );
2206 if ( $returnto === '' ) {
2207 $returnto = Title::newMainPage();
2210 if ( is_object( $returnto ) ) {
2211 $titleObj = $returnto;
2213 $titleObj = Title::newFromText( $returnto );
2215 if ( !is_object( $titleObj ) ) {
2216 $titleObj = Title::newMainPage();
2219 $this->addReturnTo( $titleObj, $returntoquery );
2223 * @param $sk Skin The given Skin
2224 * @param $includeStyle Boolean: unused
2225 * @return String: The doctype, opening <html>, and head element.
2227 public function headElement( Skin $sk, $includeStyle = true ) {
2228 global $wgOutputEncoding, $wgMimeType;
2229 global $wgUseTrackbacks, $wgHtml5;
2230 global $wgUser, $wgRequest, $wgLang;
2232 if ( $sk->commonPrintStylesheet() ) {
2233 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2235 $sk->setupUserCss( $this );
2238 $ret = Html::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2240 if ( $this->getHTMLTitle() == '' ) {
2241 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2244 $openHead = Html::openElement( 'head' );
2246 # Don't bother with the newline if $head == ''
2247 $ret .= "$openHead\n";
2251 # More succinct than <meta http-equiv=Content-Type>, has the
2253 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2255 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2258 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2260 $ret .= implode( "\n", array(
2261 $this->getHeadLinks( $sk ),
2262 $this->buildCssLinks( $sk ),
2263 $this->getHeadItems()
2266 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2267 $ret .= $this->getTitle()->trackbackRDF();
2270 $closeHead = Html::closeElement( 'head' );
2272 $ret .= "$closeHead\n";
2275 $bodyAttrs = array();
2277 # Crazy edit-on-double-click stuff
2278 $action = $wgRequest->getVal( 'action', 'view' );
2281 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2282 !in_array( $action, array( 'edit', 'submit' ) ) &&
2283 $wgUser->getOption( 'editondblclick' )
2286 $editUrl = $this->getTitle()->getLocalUrl( $sk->editUrlOptions() );
2287 $bodyAttrs['ondblclick'] = "document.location = '" .
2288 Xml::escapeJsString( $editUrl ) . "'";
2292 $dir = wfUILang()->getDir();
2293 $bodyAttrs['class'] = "mediawiki $dir";
2295 if ( $wgLang->capitalizeAllNouns() ) {
2296 # A <body> class is probably not the best way to do this . . .
2297 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2299 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2300 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2301 $bodyAttrs['class'] .= ' ns-special';
2302 } elseif ( $this->getTitle()->isTalkPage() ) {
2303 $bodyAttrs['class'] .= ' ns-talk';
2305 $bodyAttrs['class'] .= ' ns-subject';
2307 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2308 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2310 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2311 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2313 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2319 * Get a ResourceLoader object associated with this OutputPage
2321 public function getResourceLoader() {
2322 if ( is_null( $this->mResourceLoader ) ) {
2323 $this->mResourceLoader = new ResourceLoader();
2325 return $this->mResourceLoader;
2331 * @param $modules Array/string with the module name
2332 * @param $only string May be styles, messages or scripts
2333 * @param $useESI boolean
2334 * @return string html <script> and <style> tags
2336 protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
2337 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2338 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2339 // Lazy-load ResourceLoader
2340 // TODO: Should this be a static function of ResourceLoader instead?
2342 'lang' => $wgLang->getCode(),
2343 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
2344 'skin' => $skin->getSkinName(),
2347 // Propagate printable and handheld parameters if present
2348 if ( $wgRequest->getBool( 'printable' ) ) {
2349 $baseQuery['printable'] = 1;
2351 if ( $wgRequest->getBool( 'handheld' ) ) {
2352 $baseQuery['handheld'] = 1;
2355 if ( !count( $modules ) ) {
2359 if ( count( $modules ) > 1 ) {
2360 // Remove duplicate module requests
2361 $modules = array_unique( (array) $modules );
2362 // Sort module names so requests are more uniform
2365 if ( ResourceLoader::inDebugMode() ) {
2366 // Recursively call us for every item
2368 foreach ( $modules as $name ) {
2369 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2375 // Create keyed-by-group list of module objects from modules list
2377 $resourceLoader = $this->getResourceLoader();
2378 foreach ( (array) $modules as $name ) {
2379 $module = $resourceLoader->getModule( $name );
2381 $group = $module->getGroup();
2382 if ( !isset( $groups[$group] ) ) {
2383 $groups[$group] = array();
2385 $groups[$group][$name] = $module;
2388 foreach ( $groups as $group => $modules ) {
2389 $query = $baseQuery;
2390 // Special handling for user-specific groups
2391 if ( ( $group === 'user' || $group === 'private' ) && $wgUser->isLoggedIn() ) {
2392 $query['user'] = $wgUser->getName();
2395 // Create a fake request based on the one we are about to make so modules return
2396 // correct timestamp and emptiness data
2397 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2398 // Drop modules that know they're empty
2399 foreach ( $modules as $key => $module ) {
2400 if ( $module->isKnownEmpty( $context ) ) {
2401 unset( $modules[$key] );
2404 // If there are no modules left, skip this group
2405 if ( $modules === array() ) {
2409 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $modules ) );
2411 // Support inlining of private modules if configured as such
2412 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2413 if ( $only == 'styles' ) {
2414 $links .= Html::inlineStyle(
2415 $resourceLoader->makeModuleResponse( $context, $modules )
2418 $links .= Html::inlineScript(
2419 ResourceLoader::makeLoaderConditionalScript(
2420 $resourceLoader->makeModuleResponse( $context, $modules )
2426 // Special handling for the user group; because users might change their stuff
2427 // on-wiki like user pages, or user preferences; we need to find the highest
2428 // timestamp of these user-changable modules so we can ensure cache misses on change
2429 // This should NOT be done for the site group (bug 27564) because anons get that too
2430 // and we shouldn't be putting timestamps in Squid-cached HTML
2431 if ( $group === 'user' ) {
2432 // Get the maximum timestamp
2434 foreach ( $modules as $module ) {
2435 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2437 // Add a version parameter so cache will break when things change
2438 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2440 // Make queries uniform in order
2443 $url = wfAppendQuery( $wgLoadScript, $query );
2444 // Prevent the IE6 extension check from being triggered (bug 28840)
2445 // by appending a character that's invalid in Windows extensions ('*')
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( $url ) . "\n";
2459 $links .= Html::linkedScript( $url ) . "\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'.
2642 return implode( "\n", $tags );
2646 * Generate a <link rel/> for a feed.
2648 * @param $type String: feed type
2649 * @param $url String: URL to the feed
2650 * @param $text String: value of the "title" attribute
2651 * @return String: HTML fragment
2653 private function feedLink( $type, $url, $text ) {
2654 return Html::element( 'link', array(
2655 'rel' => 'alternate',
2656 'type' => "application/$type+xml",
2663 * Add a local or specified stylesheet, with the given media options.
2664 * Meant primarily for internal use...
2666 * @param $style String: URL to the file
2667 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2668 * @param $condition String: for IE conditional comments, specifying an IE version
2669 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2671 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2673 // Even though we expect the media type to be lowercase, but here we
2674 // force it to lowercase to be safe.
2676 $options['media'] = $media;
2679 $options['condition'] = $condition;
2682 $options['dir'] = $dir;
2684 $this->styles[$style] = $options;
2688 * Adds inline CSS styles
2689 * @param $style_css Mixed: inline CSS
2691 public function addInlineStyle( $style_css ){
2692 $this->mInlineStyles .= Html::inlineStyle( $style_css );
2696 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2697 * These will be applied to various media & IE conditionals.
2698 * @param $sk Skin object
2700 public function buildCssLinks( $sk ) {
2702 // Add ResourceLoader styles
2703 // Split the styles into four groups
2704 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array() );
2705 $resourceLoader = $this->getResourceLoader();
2706 foreach ( $this->getModuleStyles() as $name ) {
2707 $group = $resourceLoader->getModule( $name )->getGroup();
2708 // Modules in groups named "other" or anything different than "user", "site" or "private"
2709 // will be placed in the "other" group
2710 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
2713 // We want site, private and user styles to override dynamically added styles from modules, but we want
2714 // dynamically added styles to override statically added styles from other modules. So the order
2715 // has to be other, dynamic, site, private, user
2716 // Add statically added styles for other modules
2717 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2718 // Add normal styles added through addStyle()/addInlineStyle() here
2719 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
2720 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2721 // We use a <meta> tag with a made-up name for this because that's valid HTML
2722 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2724 // Add site, private and user styles
2725 // 'private' at present only contains user.options, so put that before 'user'
2726 // Any future private modules will likely have a similar user-specific character
2727 foreach ( array( 'site', 'private', 'user' ) as $group ) {
2728 $ret .= $this->makeResourceLoaderLink(
2729 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2735 public function buildCssLinksArray() {
2737 foreach( $this->styles as $file => $options ) {
2738 $link = $this->styleLink( $file, $options );
2740 $links[$file] = $link;
2747 * Generate \<link\> tags for stylesheets
2749 * @param $style String: URL to the file
2750 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2752 * @return String: HTML fragment
2754 protected function styleLink( $style, $options ) {
2755 if( isset( $options['dir'] ) ) {
2756 $siteDir = wfUILang()->getDir();
2757 if( $siteDir != $options['dir'] ) {
2762 if( isset( $options['media'] ) ) {
2763 $media = self::transformCssMedia( $options['media'] );
2764 if( is_null( $media ) ) {
2771 if( substr( $style, 0, 1 ) == '/' ||
2772 substr( $style, 0, 5 ) == 'http:' ||
2773 substr( $style, 0, 6 ) == 'https:' ) {
2776 global $wgStylePath, $wgStyleVersion;
2777 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2780 $link = Html::linkedStyle( $url, $media );
2782 if( isset( $options['condition'] ) ) {
2783 $condition = htmlspecialchars( $options['condition'] );
2784 $link = "<!--[if $condition]>$link<![endif]-->";
2790 * Transform "media" attribute based on request parameters
2792 * @param $media String: current value of the "media" attribute
2793 * @return String: modified value of the "media" attribute
2795 public static function transformCssMedia( $media ) {
2796 global $wgRequest, $wgHandheldForIPhone;
2798 // Switch in on-screen display for media testing
2800 'printable' => 'print',
2801 'handheld' => 'handheld',
2803 foreach( $switches as $switch => $targetMedia ) {
2804 if( $wgRequest->getBool( $switch ) ) {
2805 if( $media == $targetMedia ) {
2807 } elseif( $media == 'screen' ) {
2813 // Expand longer media queries as iPhone doesn't grok 'handheld'
2814 if( $wgHandheldForIPhone ) {
2815 $mediaAliases = array(
2816 'screen' => 'screen and (min-device-width: 481px)',
2817 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2820 if( isset( $mediaAliases[$media] ) ) {
2821 $media = $mediaAliases[$media];
2829 * Turn off regular page output and return an error reponse
2830 * for when rate limiting has triggered.
2832 public function rateLimited() {
2833 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2834 $this->setRobotPolicy( 'noindex,follow' );
2835 $this->setArticleRelated( false );
2836 $this->enableClientCache( false );
2837 $this->mRedirect = '';
2839 $this->setStatusCode( 503 );
2840 $this->addWikiMsg( 'actionthrottledtext' );
2842 $this->returnToMain( null, $this->getTitle() );
2846 * Show a warning about slave lag
2848 * If the lag is higher than $wgSlaveLagCritical seconds,
2849 * then the warning is a bit more obvious. If the lag is
2850 * lower than $wgSlaveLagWarning, then no warning is shown.
2852 * @param $lag Integer: slave lag
2854 public function showLagWarning( $lag ) {
2855 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2856 if( $lag >= $wgSlaveLagWarning ) {
2857 $message = $lag < $wgSlaveLagCritical
2860 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2861 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2866 * Add a wikitext-formatted message to the output.
2867 * This is equivalent to:
2869 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2871 public function addWikiMsg( /*...*/ ) {
2872 $args = func_get_args();
2873 $name = array_shift( $args );
2874 $this->addWikiMsgArray( $name, $args );
2878 * Add a wikitext-formatted message to the output.
2879 * Like addWikiMsg() except the parameters are taken as an array
2880 * instead of a variable argument list.
2882 * $options is passed through to wfMsgExt(), see that function for details.
2884 public function addWikiMsgArray( $name, $args, $options = array() ) {
2885 $options[] = 'parse';
2886 $text = wfMsgExt( $name, $options, $args );
2887 $this->addHTML( $text );
2891 * This function takes a number of message/argument specifications, wraps them in
2892 * some overall structure, and then parses the result and adds it to the output.
2894 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2895 * on. The subsequent arguments may either be strings, in which case they are the
2896 * message names, or arrays, in which case the first element is the message name,
2897 * and subsequent elements are the parameters to that message.
2899 * The special named parameter 'options' in a message specification array is passed
2900 * through to the $options parameter of wfMsgExt().
2902 * Don't use this for messages that are not in users interface language.
2906 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2910 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2912 * The newline after opening div is needed in some wikitext. See bug 19226.
2914 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2915 $msgSpecs = func_get_args();
2916 array_shift( $msgSpecs );
2917 $msgSpecs = array_values( $msgSpecs );
2919 foreach ( $msgSpecs as $n => $spec ) {
2921 if ( is_array( $spec ) ) {
2923 $name = array_shift( $args );
2924 if ( isset( $args['options'] ) ) {
2925 $options = $args['options'];
2926 unset( $args['options'] );
2932 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2934 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2938 * Include jQuery core. Use this to avoid loading it multiple times
2939 * before we get a usable script loader.
2941 * @param $modules Array: list of jQuery modules which should be loaded
2942 * @return Array: the list of modules which were not loaded.
2944 * @deprecated No longer needed as of 1.17
2946 public function includeJQuery( $modules = array() ) {