Reuse code from updateRestrictions.php in do_restrictions_update() instead of having...
[mediawiki.git] / includes / OutputPage.php
blob343a352c1d3dfcf32bd5ca7c95bcbba8e60b98e6
1 <?php
2 if ( !defined( 'MEDIAWIKI' ) ) {
3 die( 1 );
6 /**
7 * @todo document
8 */
9 class OutputPage {
10 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
11 var $mExtStyles = array();
12 var $mPagetitle = '', $mBodytext = '';
14 /**
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 = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
27 var $mInlineMsg = array();
29 var $mTemplateIds = array();
31 var $mAllowUserJs;
32 var $mSuppressQuickbar = false;
33 var $mDoNothing = false;
34 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
35 var $mIsArticleRelated = true;
36 protected $mParserOptions = null; // lazy initialised, use parserOptions()
38 var $mFeedLinks = array();
40 var $mEnableClientCache = true;
41 var $mArticleBodyOnly = false;
43 var $mNewSectionLink = false;
44 var $mHideNewSectionLink = false;
45 var $mNoGallery = false;
46 var $mPageTitleActionText = '';
47 var $mParseWarnings = array();
48 var $mSquidMaxage = 0;
49 var $mRevisionId = null;
50 protected $mTitle = null;
52 /**
53 * An array of stylesheet filenames (relative from skins path), with options
54 * for CSS media, IE conditions, and RTL/LTR direction.
55 * For internal use; add settings in the skin via $this->addStyle()
57 var $styles = array();
59 /**
60 * Whether to load jQuery core.
62 protected $mJQueryDone = false;
64 private $mIndexPolicy = 'index';
65 private $mFollowPolicy = 'follow';
66 private $mVaryHeader = array(
67 'Accept-Encoding' => array( 'list-contains=gzip' ),
68 'Cookie' => null
71 /**
72 * Constructor
73 * Initialise private variables
75 function __construct() {
76 global $wgAllowUserJs;
77 $this->mAllowUserJs = $wgAllowUserJs;
80 /**
81 * Redirect to $url rather than displaying the normal page
83 * @param $url String: URL
84 * @param $responsecode String: HTTP status code
86 public function redirect( $url, $responsecode = '302' ) {
87 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
88 $this->mRedirect = str_replace( "\n", '', $url );
89 $this->mRedirectCode = $responsecode;
92 /**
93 * Get the URL to redirect to, or an empty string if not redirect URL set
95 * @return String
97 public function getRedirect() {
98 return $this->mRedirect;
102 * Set the HTTP status code to send with the output.
104 * @param $statusCode Integer
105 * @return nothing
107 public function setStatusCode( $statusCode ) {
108 $this->mStatusCode = $statusCode;
112 * Add a new <meta> tag
113 * To add an http-equiv meta tag, precede the name with "http:"
115 * @param $name tag name
116 * @param $val tag value
118 function addMeta( $name, $val ) {
119 array_push( $this->mMetatags, array( $name, $val ) );
123 * Add a keyword or a list of keywords in the page header
125 * @param $text String or array of strings
127 function addKeyword( $text ) {
128 if( is_array( $text ) ) {
129 $this->mKeywords = array_merge( $this->mKeywords, $text );
130 } else {
131 array_push( $this->mKeywords, $text );
136 * Add a new \<link\> tag to the page header
138 * @param $linkarr Array: associative array of attributes.
140 function addLink( $linkarr ) {
141 array_push( $this->mLinktags, $linkarr );
145 * Add a new \<link\> with "rel" attribute set to "meta"
147 * @param $linkarr Array: associative array mapping attribute names to their
148 * values, both keys and values will be escaped, and the
149 * "rel" attribute will be automatically added
151 function addMetadataLink( $linkarr ) {
152 # note: buggy CC software only reads first "meta" link
153 static $haveMeta = false;
154 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
155 $this->addLink( $linkarr );
156 $haveMeta = true;
160 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
162 * @param $script String: raw HTML
164 function addScript( $script ) {
165 $this->mScripts .= $script . "\n";
169 * Register and add a stylesheet from an extension directory.
171 * @param $url String path to sheet. Provide either a full url (beginning
172 * with 'http', etc) or a relative path from the document root
173 * (beginning with '/'). Otherwise it behaves identically to
174 * addStyle() and draws from the /skins folder.
176 public function addExtensionStyle( $url ) {
177 array_push( $this->mExtStyles, $url );
181 * Get all links added by extensions
183 * @return Array
185 function getExtStyle() {
186 return $this->mExtStyles;
190 * Add a JavaScript file out of skins/common, or a given relative path.
192 * @param $file String: filename in skins/common or complete on-server path
193 * (/foo/bar.js)
194 * @param $version String: style version of the file. Defaults to $wgStyleVersion
196 public function addScriptFile( $file, $version = null ) {
197 global $wgStylePath, $wgStyleVersion;
198 // See if $file parameter is an absolute URL or begins with a slash
199 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
200 $path = $file;
201 } else {
202 $path = "{$wgStylePath}/common/{$file}";
204 if ( is_null( $version ) )
205 $version = $wgStyleVersion;
206 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
210 * Add a self-contained script tag with the given contents
212 * @param $script String: JavaScript text, no <script> tags
214 public function addInlineScript( $script ) {
215 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
219 * Get all registered JS and CSS tags for the header.
221 * @return String
223 function getScript() {
224 return $this->mScripts . $this->getHeadItems();
228 * Get all header items in a string
230 * @return String
232 function getHeadItems() {
233 $s = '';
234 foreach ( $this->mHeadItems as $item ) {
235 $s .= $item;
237 return $s;
241 * Add or replace an header item to the output
243 * @param $name String: item name
244 * @param $value String: raw HTML
246 public function addHeadItem( $name, $value ) {
247 $this->mHeadItems[$name] = $value;
251 * Check if the header item $name is already set
253 * @param $name String: item name
254 * @return Boolean
256 public function hasHeadItem( $name ) {
257 return isset( $this->mHeadItems[$name] );
261 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
263 * @param $tag String: value of "ETag" header
265 function setETag( $tag ) {
266 $this->mETag = $tag;
270 * Set whether the output should only contain the body of the article,
271 * without any skin, sidebar, etc.
272 * Used e.g. when calling with "action=render".
274 * @param $only Boolean: whether to output only the body of the article
276 public function setArticleBodyOnly( $only ) {
277 $this->mArticleBodyOnly = $only;
281 * Return whether the output will contain only the body of the article
283 * @return Boolean
285 public function getArticleBodyOnly() {
286 return $this->mArticleBodyOnly;
290 * checkLastModified tells the client to use the client-cached page if
291 * possible. If sucessful, the OutputPage is disabled so that
292 * any future call to OutputPage->output() have no effect.
294 * Side effect: sets mLastModified for Last-Modified header
296 * @return Boolean: true iff cache-ok headers was sent.
298 public function checkLastModified( $timestamp ) {
299 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
301 if ( !$timestamp || $timestamp == '19700101000000' ) {
302 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
303 return false;
305 if( !$wgCachePages ) {
306 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
307 return false;
309 if( $wgUser->getOption( 'nocache' ) ) {
310 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
311 return false;
314 $timestamp = wfTimestamp( TS_MW, $timestamp );
315 $modifiedTimes = array(
316 'page' => $timestamp,
317 'user' => $wgUser->getTouched(),
318 'epoch' => $wgCacheEpoch
320 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
322 $maxModified = max( $modifiedTimes );
323 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
325 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
326 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
327 return false;
330 # Make debug info
331 $info = '';
332 foreach ( $modifiedTimes as $name => $value ) {
333 if ( $info !== '' ) {
334 $info .= ', ';
336 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
339 # IE sends sizes after the date like this:
340 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
341 # this breaks strtotime().
342 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
344 wfSuppressWarnings(); // E_STRICT system time bitching
345 $clientHeaderTime = strtotime( $clientHeader );
346 wfRestoreWarnings();
347 if ( !$clientHeaderTime ) {
348 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
349 return false;
351 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
353 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
354 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
355 wfDebug( __METHOD__ . ": effective Last-Modified: " .
356 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
357 if( $clientHeaderTime < $maxModified ) {
358 wfDebug( __METHOD__ . ": STALE, $info\n", false );
359 return false;
362 # Not modified
363 # Give a 304 response code and disable body output
364 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
365 ini_set( 'zlib.output_compression', 0 );
366 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
367 $this->sendCacheControl();
368 $this->disable();
370 // Don't output a compressed blob when using ob_gzhandler;
371 // it's technically against HTTP spec and seems to confuse
372 // Firefox when the response gets split over two packets.
373 wfClearOutputBuffers();
375 return true;
379 * Override the last modified timestamp
381 * @param $timestamp String: new timestamp, in a format readable by
382 * wfTimestamp()
384 public function setLastModified( $timestamp ) {
385 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
389 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
391 * @param $policy String: the literal string to output as the contents of
392 * the meta tag. Will be parsed according to the spec and output in
393 * standardized form.
394 * @return null
396 public function setRobotPolicy( $policy ) {
397 $policy = Article::formatRobotPolicy( $policy );
399 if( isset( $policy['index'] ) ) {
400 $this->setIndexPolicy( $policy['index'] );
402 if( isset( $policy['follow'] ) ) {
403 $this->setFollowPolicy( $policy['follow'] );
408 * Set the index policy for the page, but leave the follow policy un-
409 * touched.
411 * @param $policy string Either 'index' or 'noindex'.
412 * @return null
414 public function setIndexPolicy( $policy ) {
415 $policy = trim( $policy );
416 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
417 $this->mIndexPolicy = $policy;
422 * Set the follow policy for the page, but leave the index policy un-
423 * touched.
425 * @param $policy String: either 'follow' or 'nofollow'.
426 * @return null
428 public function setFollowPolicy( $policy ) {
429 $policy = trim( $policy );
430 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
431 $this->mFollowPolicy = $policy;
436 * Set the new value of the "action text", this will be added to the
437 * "HTML title", separated from it with " - ".
439 * @param $text String: new value of the "action text"
441 public function setPageTitleActionText( $text ) {
442 $this->mPageTitleActionText = $text;
446 * Get the value of the "action text"
448 * @return String
450 public function getPageTitleActionText() {
451 if ( isset( $this->mPageTitleActionText ) ) {
452 return $this->mPageTitleActionText;
457 * "HTML title" means the contents of <title>.
458 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
460 public function setHTMLTitle( $name ) {
461 $this->mHTMLtitle = $name;
465 * Return the "HTML title", i.e. the content of the <title> tag.
467 * @return String
469 public function getHTMLTitle() {
470 return $this->mHTMLtitle;
474 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
475 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
476 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
477 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
479 public function setPageTitle( $name ) {
480 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
481 # but leave "<i>foobar</i>" alone
482 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
483 $this->mPagetitle = $nameWithTags;
485 $taction = $this->getPageTitleActionText();
486 if( !empty( $taction ) ) {
487 $name .= ' - '.$taction;
490 # change "<i>foo&amp;bar</i>" to "foo&bar"
491 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
495 * Return the "page title", i.e. the content of the \<h1\> tag.
497 * @return String
499 public function getPageTitle() {
500 return $this->mPagetitle;
504 * Set the Title object to use
506 * @param $t Title object
508 public function setTitle( $t ) {
509 $this->mTitle = $t;
513 * Get the Title object used in this instance
515 * @return Title
517 public function getTitle() {
518 if ( $this->mTitle instanceof Title ) {
519 return $this->mTitle;
520 } else {
521 wfDebug( __METHOD__ . " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
522 global $wgTitle;
523 return $wgTitle;
528 * Replace the subtile with $str
530 * @param $str String: new value of the subtitle
532 public function setSubtitle( $str ) {
533 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
537 * Add $str to the subtitle
539 * @param $str String to add to the subtitle
541 public function appendSubtitle( $str ) {
542 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
546 * Get the subtitle
548 * @return String
550 public function getSubtitle() {
551 return $this->mSubtitle;
555 * Set the page as printable, i.e. it'll be displayed with with all
556 * print styles included
558 public function setPrintable() {
559 $this->mPrintable = true;
563 * Return whether the page is "printable"
565 * @return Boolean
567 public function isPrintable() {
568 return $this->mPrintable;
572 * Disable output completely, i.e. calling output() will have no effect
574 public function disable() {
575 $this->mDoNothing = true;
579 * Return whether the output will be completely disabled
581 * @return Boolean
583 public function isDisabled() {
584 return $this->mDoNothing;
588 * Show an "add new section" link?
590 * @return Boolean
592 public function showNewSectionLink() {
593 return $this->mNewSectionLink;
597 * Forcibly hide the new section link?
599 * @return Boolean
601 public function forceHideNewSectionLink() {
602 return $this->mHideNewSectionLink;
606 * Add or remove feed links in the page header
607 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
608 * for the new version
609 * @see addFeedLink()
611 * @param $show Boolean: true: add default feeds, false: remove all feeds
613 public function setSyndicated( $show = true ) {
614 if ( $show ) {
615 $this->setFeedAppendQuery( false );
616 } else {
617 $this->mFeedLinks = array();
622 * Add default feeds to the page header
623 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
624 * for the new version
625 * @see addFeedLink()
627 * @param $val String: query to append to feed links or false to output
628 * default links
630 public function setFeedAppendQuery( $val ) {
631 global $wgAdvertisedFeedTypes;
633 $this->mFeedLinks = array();
635 foreach ( $wgAdvertisedFeedTypes as $type ) {
636 $query = "feed=$type";
637 if ( is_string( $val ) ) {
638 $query .= '&' . $val;
640 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
645 * Add a feed link to the page header
647 * @param $format String: feed type, should be a key of $wgFeedClasses
648 * @param $href String: URL
650 public function addFeedLink( $format, $href ) {
651 global $wgAdvertisedFeedTypes;
653 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
654 $this->mFeedLinks[$format] = $href;
659 * Should we output feed links for this page?
660 * @return Boolean
662 public function isSyndicated() {
663 return count( $this->mFeedLinks ) > 0;
667 * Return URLs for each supported syndication format for this page.
668 * @return array associating format keys with URLs
670 public function getSyndicationLinks() {
671 return $this->mFeedLinks;
675 * Will currently always return null
677 * @return null
679 public function getFeedAppendQuery() {
680 return $this->mFeedLinksAppendQuery;
684 * Set whether the displayed content is related to the source of the
685 * corresponding article on the wiki
686 * Setting true will cause the change "article related" toggle to true
688 * @param $v Boolean
690 public function setArticleFlag( $v ) {
691 $this->mIsarticle = $v;
692 if ( $v ) {
693 $this->mIsArticleRelated = $v;
698 * Return whether the content displayed page is related to the source of
699 * the corresponding article on the wiki
701 * @return Boolean
703 public function isArticle() {
704 return $this->mIsarticle;
708 * Set whether this page is related an article on the wiki
709 * Setting false will cause the change of "article flag" toggle to false
711 * @param $v Boolean
713 public function setArticleRelated( $v ) {
714 $this->mIsArticleRelated = $v;
715 if ( !$v ) {
716 $this->mIsarticle = false;
721 * Return whether this page is related an article on the wiki
723 * @return Boolean
725 public function isArticleRelated() {
726 return $this->mIsArticleRelated;
730 * Add new language links
732 * @param $newLinkArray Associative array mapping language code to the page
733 * name
735 public function addLanguageLinks( $newLinkArray ) {
736 $this->mLanguageLinks += $newLinkArray;
740 * Reset the language links and add new language links
742 * @param $newLinkArray Associative array mapping language code to the page
743 * name
745 public function setLanguageLinks( $newLinkArray ) {
746 $this->mLanguageLinks = $newLinkArray;
750 * Get the list of language links
752 * @return Associative array mapping language code to the page name
754 public function getLanguageLinks() {
755 return $this->mLanguageLinks;
759 * Add an array of categories, with names in the keys
761 * @param $categories Associative array mapping category name to its sort key
763 public function addCategoryLinks( $categories ) {
764 global $wgUser, $wgContLang;
766 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
767 return;
770 # Add the links to a LinkBatch
771 $arr = array( NS_CATEGORY => $categories );
772 $lb = new LinkBatch;
773 $lb->setArray( $arr );
775 # Fetch existence plus the hiddencat property
776 $dbr = wfGetDB( DB_SLAVE );
777 $pageTable = $dbr->tableName( 'page' );
778 $where = $lb->constructSet( 'page', $dbr );
779 $propsTable = $dbr->tableName( 'page_props' );
780 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
781 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
782 $res = $dbr->query( $sql, __METHOD__ );
784 # Add the results to the link cache
785 $lb->addResultToCache( LinkCache::singleton(), $res );
787 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
788 $categories = array_combine(
789 array_keys( $categories ),
790 array_fill( 0, count( $categories ), 'normal' )
793 # Mark hidden categories
794 foreach ( $res as $row ) {
795 if ( isset( $row->pp_value ) ) {
796 $categories[$row->page_title] = 'hidden';
800 # Add the remaining categories to the skin
801 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
802 $sk = $wgUser->getSkin();
803 foreach ( $categories as $category => $type ) {
804 $origcategory = $category;
805 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
806 $wgContLang->findVariantLink( $category, $title, true );
807 if ( $category != $origcategory ) {
808 if ( array_key_exists( $category, $categories ) ) {
809 continue;
812 $text = $wgContLang->convertHtml( $title->getText() );
813 $this->mCategories[] = $title->getText();
814 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
820 * Reset the category links (but not the category list) and add $categories
822 * @param $categories Associative array mapping category name to its sort key
824 public function setCategoryLinks( $categories ) {
825 $this->mCategoryLinks = array();
826 $this->addCategoryLinks( $categories );
830 * Get the list of category links, in a 2-D array with the following format:
831 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
832 * hidden categories) and $link a HTML fragment with a link to the category
833 * page
835 * @return Array
837 public function getCategoryLinks() {
838 return $this->mCategoryLinks;
842 * Get the list of category names this page belongs to
844 * @return Array of strings
846 public function getCategories() {
847 return $this->mCategories;
851 * Suppress the quickbar from the output, only for skin supporting
852 * the quickbar
854 public function suppressQuickbar() {
855 $this->mSuppressQuickbar = true;
859 * Return whether the quickbar should be suppressed from the output
861 * @return Boolean
863 public function isQuickbarSuppressed() {
864 return $this->mSuppressQuickbar;
868 * Remove user JavaScript from scripts to load
870 public function disallowUserJs() {
871 $this->mAllowUserJs = false;
875 * Return whether user JavaScript is allowed for this page
877 * @return Boolean
879 public function isUserJsAllowed() {
880 return $this->mAllowUserJs;
884 * Prepend $text to the body HTML
886 * @param $text String: HTML
888 public function prependHTML( $text ) {
889 $this->mBodytext = $text . $this->mBodytext;
893 * Append $text to the body HTML
895 * @param $text String: HTML
897 public function addHTML( $text ) {
898 $this->mBodytext .= $text;
902 * Clear the body HTML
904 public function clearHTML() {
905 $this->mBodytext = '';
909 * Get the body HTML
911 * @return String: HTML
913 public function getHTML() {
914 return $this->mBodytext;
918 * Add $text to the debug output
920 * @param $text String: debug text
922 public function debug( $text ) {
923 $this->mDebugtext .= $text;
927 * @deprecated use parserOptions() instead
929 public function setParserOptions( $options ) {
930 wfDeprecated( __METHOD__ );
931 return $this->parserOptions( $options );
935 * Get/set the ParserOptions object to use for wikitext parsing
937 * @param $options either the ParserOption to use or null to only get the
938 * current ParserOption object
939 * @return current ParserOption object
941 public function parserOptions( $options = null ) {
942 if ( !$this->mParserOptions ) {
943 $this->mParserOptions = new ParserOptions;
945 return wfSetVar( $this->mParserOptions, $options );
949 * Set the revision ID which will be seen by the wiki text parser
950 * for things such as embedded {{REVISIONID}} variable use.
952 * @param $revid Mixed: an positive integer, or null
953 * @return Mixed: previous value
955 public function setRevisionId( $revid ) {
956 $val = is_null( $revid ) ? null : intval( $revid );
957 return wfSetVar( $this->mRevisionId, $val );
961 * Get the current revision ID
963 * @return Integer
965 public function getRevisionId() {
966 return $this->mRevisionId;
970 * Convert wikitext to HTML and add it to the buffer
971 * Default assumes that the current page title will be used.
973 * @param $text String
974 * @param $linestart Boolean: is this the start of a line?
976 public function addWikiText( $text, $linestart = true ) {
977 $title = $this->getTitle(); // Work arround E_STRICT
978 $this->addWikiTextTitle( $text, $title, $linestart );
982 * Add wikitext with a custom Title object
984 * @param $text String: wikitext
985 * @param $title Title object
986 * @param $linestart Boolean: is this the start of a line?
988 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
989 $this->addWikiTextTitle( $text, $title, $linestart );
993 * Add wikitext with a custom Title object and
995 * @param $text String: wikitext
996 * @param $title Title object
997 * @param $linestart Boolean: is this the start of a line?
999 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1000 $this->addWikiTextTitle( $text, $title, $linestart, true );
1004 * Add wikitext with tidy enabled
1006 * @param $text String: wikitext
1007 * @param $linestart Boolean: is this the start of a line?
1009 public function addWikiTextTidy( $text, $linestart = true ) {
1010 $title = $this->getTitle();
1011 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1015 * Add wikitext with a custom Title object
1017 * @param $text String: wikitext
1018 * @param $title Title object
1019 * @param $linestart Boolean: is this the start of a line?
1020 * @param $tidy Boolean: whether to use tidy
1022 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1023 global $wgParser;
1025 wfProfileIn( __METHOD__ );
1027 wfIncrStats( 'pcache_not_possible' );
1029 $popts = $this->parserOptions();
1030 $oldTidy = $popts->setTidy( $tidy );
1032 $parserOutput = $wgParser->parse(
1033 $text, $title, $popts,
1034 $linestart, true, $this->mRevisionId
1037 $popts->setTidy( $oldTidy );
1039 $this->addParserOutput( $parserOutput );
1041 wfProfileOut( __METHOD__ );
1045 * Add wikitext to the buffer, assuming that this is the primary text for a page view
1046 * Saves the text into the parser cache if possible.
1048 * @param $text String: wikitext
1049 * @param $article Article object
1050 * @param $cache Boolean
1051 * @deprecated Use Article::outputWikitext
1053 public function addPrimaryWikiText( $text, $article, $cache = true ) {
1054 global $wgParser;
1056 wfDeprecated( __METHOD__ );
1058 $popts = $this->parserOptions();
1059 $popts->setTidy( true );
1060 $parserOutput = $wgParser->parse(
1061 $text, $article->mTitle,
1062 $popts, true, true, $this->mRevisionId
1064 $popts->setTidy( false );
1065 if ( $cache && $article && $parserOutput->isCacheable() ) {
1066 $parserCache = ParserCache::singleton();
1067 $parserCache->save( $parserOutput, $article, $popts );
1070 $this->addParserOutput( $parserOutput );
1074 * @deprecated use addWikiTextTidy()
1076 public function addSecondaryWikiText( $text, $linestart = true ) {
1077 wfDeprecated( __METHOD__ );
1078 $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
1082 * Add a ParserOutput object, but without Html
1084 * @param $parserOutput ParserOutput object
1086 public function addParserOutputNoText( &$parserOutput ) {
1087 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1088 $this->addCategoryLinks( $parserOutput->getCategories() );
1089 $this->mNewSectionLink = $parserOutput->getNewSection();
1090 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1092 $this->mParseWarnings = $parserOutput->getWarnings();
1093 if ( !$parserOutput->isCacheable() ) {
1094 $this->enableClientCache( false );
1096 $this->mNoGallery = $parserOutput->getNoGallery();
1097 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1098 // Versioning...
1099 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1100 if ( isset( $this->mTemplateIds[$ns] ) ) {
1101 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1102 } else {
1103 $this->mTemplateIds[$ns] = $dbks;
1107 // Hooks registered in the object
1108 global $wgParserOutputHooks;
1109 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1110 list( $hookName, $data ) = $hookInfo;
1111 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1112 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1116 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1120 * Add a ParserOutput object
1122 * @param $parserOutput ParserOutput
1124 function addParserOutput( &$parserOutput ) {
1125 $this->addParserOutputNoText( $parserOutput );
1126 $text = $parserOutput->getText();
1127 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1128 $this->addHTML( $text );
1133 * Add the output of a QuickTemplate to the output buffer
1135 * @param $template QuickTemplate
1137 public function addTemplate( &$template ) {
1138 ob_start();
1139 $template->execute();
1140 $this->addHTML( ob_get_contents() );
1141 ob_end_clean();
1145 * Parse wikitext and return the HTML.
1147 * @param $text String
1148 * @param $linestart Boolean: is this the start of a line?
1149 * @param $interface Boolean: use interface language ($wgLang instead of
1150 * $wgContLang) while parsing language sensitive magic
1151 * words like GRAMMAR and PLURAL
1152 * @return String: HTML
1154 public function parse( $text, $linestart = true, $interface = false ) {
1155 global $wgParser;
1156 if( is_null( $this->getTitle() ) ) {
1157 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1159 $popts = $this->parserOptions();
1160 if ( $interface ) {
1161 $popts->setInterfaceMessage( true );
1163 $parserOutput = $wgParser->parse(
1164 $text, $this->getTitle(), $popts,
1165 $linestart, true, $this->mRevisionId
1167 if ( $interface ) {
1168 $popts->setInterfaceMessage( false );
1170 return $parserOutput->getText();
1174 * Parse wikitext, strip paragraphs, and return the HTML.
1176 * @param $text String
1177 * @param $linestart Boolean: is this the start of a line?
1178 * @param $interface Boolean: use interface language ($wgLang instead of
1179 * $wgContLang) while parsing language sensitive magic
1180 * words like GRAMMAR and PLURAL
1181 * @return String: HTML
1183 public function parseInline( $text, $linestart = true, $interface = false ) {
1184 $parsed = $this->parse( $text, $linestart, $interface );
1186 $m = array();
1187 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1188 $parsed = $m[1];
1191 return $parsed;
1195 * @deprecated
1197 * @param $article Article
1198 * @return Boolean: true if successful, else false.
1200 public function tryParserCache( &$article ) {
1201 wfDeprecated( __METHOD__ );
1202 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
1204 if ( $parserOutput !== false ) {
1205 $this->addParserOutput( $parserOutput );
1206 return true;
1207 } else {
1208 return false;
1213 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1215 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1217 public function setSquidMaxage( $maxage ) {
1218 $this->mSquidMaxage = $maxage;
1222 * Use enableClientCache(false) to force it to send nocache headers
1224 * @param $state ??
1226 public function enableClientCache( $state ) {
1227 return wfSetVar( $this->mEnableClientCache, $state );
1231 * Get the list of cookies that will influence on the cache
1233 * @return Array
1235 function getCacheVaryCookies() {
1236 global $wgCookiePrefix, $wgCacheVaryCookies;
1237 static $cookies;
1238 if ( $cookies === null ) {
1239 $cookies = array_merge(
1240 array(
1241 "{$wgCookiePrefix}Token",
1242 "{$wgCookiePrefix}LoggedOut",
1243 session_name()
1245 $wgCacheVaryCookies
1247 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1249 return $cookies;
1253 * Return whether this page is not cacheable because "useskin" or "uselang"
1254 * URL parameters were passed.
1256 * @return Boolean
1258 function uncacheableBecauseRequestVars() {
1259 global $wgRequest;
1260 return $wgRequest->getText( 'useskin', false ) === false
1261 && $wgRequest->getText( 'uselang', false ) === false;
1265 * Check if the request has a cache-varying cookie header
1266 * If it does, it's very important that we don't allow public caching
1268 * @return Boolean
1270 function haveCacheVaryCookies() {
1271 global $wgRequest;
1272 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1273 if ( $cookieHeader === false ) {
1274 return false;
1276 $cvCookies = $this->getCacheVaryCookies();
1277 foreach ( $cvCookies as $cookieName ) {
1278 # Check for a simple string match, like the way squid does it
1279 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1280 wfDebug( __METHOD__ . ": found $cookieName\n" );
1281 return true;
1284 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1285 return false;
1289 * Add an HTTP header that will influence on the cache
1291 * @param $header String: header name
1292 * @param $option either an Array or null
1294 public function addVaryHeader( $header, $option = null ) {
1295 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1296 $this->mVaryHeader[$header] = $option;
1297 } elseif( is_array( $option ) ) {
1298 if( is_array( $this->mVaryHeader[$header] ) ) {
1299 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1300 } else {
1301 $this->mVaryHeader[$header] = $option;
1304 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1308 * Get a complete X-Vary-Options header
1310 * @return String
1312 public function getXVO() {
1313 $cvCookies = $this->getCacheVaryCookies();
1315 $cookiesOption = array();
1316 foreach ( $cvCookies as $cookieName ) {
1317 $cookiesOption[] = 'string-contains=' . $cookieName;
1319 $this->addVaryHeader( 'Cookie', $cookiesOption );
1321 $headers = array();
1322 foreach( $this->mVaryHeader as $header => $option ) {
1323 $newheader = $header;
1324 if( is_array( $option ) ) {
1325 $newheader .= ';' . implode( ';', $option );
1327 $headers[] = $newheader;
1329 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1331 return $xvo;
1335 * bug 21672: Add Accept-Language to Vary and XVO headers
1336 * if there's no 'variant' parameter existed in GET.
1338 * For example:
1339 * /w/index.php?title=Main_page should always be served; but
1340 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1342 function addAcceptLanguage() {
1343 global $wgRequest, $wgContLang;
1344 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1345 $variants = $wgContLang->getVariants();
1346 $aloption = array();
1347 foreach ( $variants as $variant ) {
1348 if( $variant === $wgContLang->getCode() ) {
1349 continue;
1350 } else {
1351 $aloption[] = "string-contains=$variant";
1354 $this->addVaryHeader( 'Accept-Language', $aloption );
1359 * Send cache control HTTP headers
1361 public function sendCacheControl() {
1362 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1364 $response = $wgRequest->response();
1365 if ( $wgUseETag && $this->mETag ) {
1366 $response->header( "ETag: $this->mETag" );
1369 $this->addAcceptLanguage();
1371 # don't serve compressed data to clients who can't handle it
1372 # maintain different caches for logged-in users and non-logged in ones
1373 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1375 if ( $wgUseXVO ) {
1376 # Add an X-Vary-Options header for Squid with Wikimedia patches
1377 $response->header( $this->getXVO() );
1380 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1382 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1383 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1386 if ( $wgUseESI ) {
1387 # We'll purge the proxy cache explicitly, but require end user agents
1388 # to revalidate against the proxy on each visit.
1389 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1390 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1391 # start with a shorter timeout for initial testing
1392 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1393 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1394 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1395 } else {
1396 # We'll purge the proxy cache for anons explicitly, but require end user agents
1397 # to revalidate against the proxy on each visit.
1398 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1399 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1400 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1401 # start with a shorter timeout for initial testing
1402 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1403 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1405 } else {
1406 # We do want clients to cache if they can, but they *must* check for updates
1407 # on revisiting the page.
1408 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1409 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1410 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1412 if($this->mLastModified) {
1413 $response->header( "Last-Modified: {$this->mLastModified}" );
1415 } else {
1416 wfDebug( __METHOD__ . ": no caching **\n", false );
1418 # In general, the absence of a last modified header should be enough to prevent
1419 # the client from using its cache. We send a few other things just to make sure.
1420 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1421 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1422 $response->header( 'Pragma: no-cache' );
1427 * Get the message associed with the HTTP response code $code
1429 * @param $code Integer: status code
1430 * @return String or null: message or null if $code is not in the list of
1431 * messages
1433 public static function getStatusMessage( $code ) {
1434 static $statusMessage = array(
1435 100 => 'Continue',
1436 101 => 'Switching Protocols',
1437 102 => 'Processing',
1438 200 => 'OK',
1439 201 => 'Created',
1440 202 => 'Accepted',
1441 203 => 'Non-Authoritative Information',
1442 204 => 'No Content',
1443 205 => 'Reset Content',
1444 206 => 'Partial Content',
1445 207 => 'Multi-Status',
1446 300 => 'Multiple Choices',
1447 301 => 'Moved Permanently',
1448 302 => 'Found',
1449 303 => 'See Other',
1450 304 => 'Not Modified',
1451 305 => 'Use Proxy',
1452 307 => 'Temporary Redirect',
1453 400 => 'Bad Request',
1454 401 => 'Unauthorized',
1455 402 => 'Payment Required',
1456 403 => 'Forbidden',
1457 404 => 'Not Found',
1458 405 => 'Method Not Allowed',
1459 406 => 'Not Acceptable',
1460 407 => 'Proxy Authentication Required',
1461 408 => 'Request Timeout',
1462 409 => 'Conflict',
1463 410 => 'Gone',
1464 411 => 'Length Required',
1465 412 => 'Precondition Failed',
1466 413 => 'Request Entity Too Large',
1467 414 => 'Request-URI Too Large',
1468 415 => 'Unsupported Media Type',
1469 416 => 'Request Range Not Satisfiable',
1470 417 => 'Expectation Failed',
1471 422 => 'Unprocessable Entity',
1472 423 => 'Locked',
1473 424 => 'Failed Dependency',
1474 500 => 'Internal Server Error',
1475 501 => 'Not Implemented',
1476 502 => 'Bad Gateway',
1477 503 => 'Service Unavailable',
1478 504 => 'Gateway Timeout',
1479 505 => 'HTTP Version Not Supported',
1480 507 => 'Insufficient Storage'
1482 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1486 * Finally, all the text has been munged and accumulated into
1487 * the object, let's actually output it:
1489 public function output() {
1490 global $wgUser, $wgOutputEncoding, $wgRequest;
1491 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1492 global $wgUseAjax, $wgAjaxWatch;
1493 global $wgEnableMWSuggest, $wgUniversalEditButton;
1494 global $wgArticle, $wgJQueryOnEveryPage;
1496 if( $this->mDoNothing ) {
1497 return;
1499 wfProfileIn( __METHOD__ );
1500 if ( $this->mRedirect != '' ) {
1501 # Standards require redirect URLs to be absolute
1502 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1503 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1504 if( !$wgDebugRedirects ) {
1505 $message = self::getStatusMessage( $this->mRedirectCode );
1506 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1508 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1510 $this->sendCacheControl();
1512 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1513 if( $wgDebugRedirects ) {
1514 $url = htmlspecialchars( $this->mRedirect );
1515 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1516 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1517 print "</body>\n</html>\n";
1518 } else {
1519 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1521 wfProfileOut( __METHOD__ );
1522 return;
1523 } elseif ( $this->mStatusCode ) {
1524 $message = self::getStatusMessage( $this->mStatusCode );
1525 if ( $message ) {
1526 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1530 $sk = $wgUser->getSkin();
1532 if ( $wgUseAjax ) {
1533 $this->addScriptFile( 'ajax.js' );
1535 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1537 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1538 $this->includeJQuery();
1539 $this->addScriptFile( 'ajaxwatch.js' );
1542 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1543 $this->addScriptFile( 'mwsuggest.js' );
1547 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1548 $this->addScriptFile( 'rightclickedit.js' );
1551 if( $wgUniversalEditButton ) {
1552 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1553 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1554 // Original UniversalEditButton
1555 $msg = wfMsg( 'edit' );
1556 $this->addLink( array(
1557 'rel' => 'alternate',
1558 'type' => 'application/x-wiki',
1559 'title' => $msg,
1560 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1561 ) );
1562 // Alternate edit link
1563 $this->addLink( array(
1564 'rel' => 'edit',
1565 'title' => $msg,
1566 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1567 ) );
1571 if ( $wgJQueryOnEveryPage ) {
1572 $this->includeJQuery();
1575 # Buffer output; final headers may depend on later processing
1576 ob_start();
1578 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1579 $wgRequest->response()->header( 'Content-language: ' . $wgContLanguageCode );
1581 if ( $this->mArticleBodyOnly ) {
1582 $this->out( $this->mBodytext );
1583 } else {
1584 // Hook that allows last minute changes to the output page, e.g.
1585 // adding of CSS or Javascript by extensions.
1586 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1588 wfProfileIn( 'Output-skin' );
1589 $sk->outputPage( $this );
1590 wfProfileOut( 'Output-skin' );
1593 $this->sendCacheControl();
1594 ob_end_flush();
1595 wfProfileOut( __METHOD__ );
1599 * Actually output something with print(). Performs an iconv to the
1600 * output encoding, if needed.
1602 * @param $ins String: the string to output
1604 public function out( $ins ) {
1605 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1606 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1607 $outs = $ins;
1608 } else {
1609 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1610 if ( false === $outs ) {
1611 $outs = $ins;
1614 print $outs;
1618 * @todo document
1620 public static function setEncodings() {
1621 global $wgInputEncoding, $wgOutputEncoding;
1623 $wgInputEncoding = strtolower( $wgInputEncoding );
1625 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1626 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1627 return;
1629 $wgOutputEncoding = $wgInputEncoding;
1633 * @deprecated use wfReportTime() instead.
1635 * @return String
1637 public function reportTime() {
1638 wfDeprecated( __METHOD__ );
1639 $time = wfReportTime();
1640 return $time;
1644 * Produce a "user is blocked" page.
1646 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1647 * @return nothing
1649 function blockedPage( $return = true ) {
1650 global $wgUser, $wgContLang, $wgLang;
1652 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1653 $this->setRobotPolicy( 'noindex,nofollow' );
1654 $this->setArticleRelated( false );
1656 $name = User::whoIs( $wgUser->blockedBy() );
1657 $reason = $wgUser->blockedFor();
1658 if( $reason == '' ) {
1659 $reason = wfMsg( 'blockednoreason' );
1661 $blockTimestamp = $wgLang->timeanddate(
1662 wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
1664 $ip = wfGetIP();
1666 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1668 $blockid = $wgUser->mBlock->mId;
1670 $blockExpiry = $wgUser->mBlock->mExpiry;
1671 if ( $blockExpiry == 'infinity' ) {
1672 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1673 // Search for localization in 'ipboptions'
1674 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1675 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1676 if ( strpos( $option, ':' ) === false ) {
1677 continue;
1679 list( $show, $value ) = explode( ':', $option );
1680 if ( $value == 'infinite' || $value == 'indefinite' ) {
1681 $blockExpiry = $show;
1682 break;
1685 } else {
1686 $blockExpiry = $wgLang->timeanddate(
1687 wfTimestamp( TS_MW, $blockExpiry ),
1688 true
1692 if ( $wgUser->mBlock->mAuto ) {
1693 $msg = 'autoblockedtext';
1694 } else {
1695 $msg = 'blockedtext';
1698 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1699 * This could be a username, an IP range, or a single IP. */
1700 $intended = $wgUser->mBlock->mAddress;
1702 $this->addWikiMsg(
1703 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1704 $intended, $blockTimestamp
1707 # Don't auto-return to special pages
1708 if( $return ) {
1709 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1710 $this->returnToMain( null, $return );
1715 * Output a standard error page
1717 * @param $title String: message key for page title
1718 * @param $msg String: message key for page text
1719 * @param $params Array: message parameters
1721 public function showErrorPage( $title, $msg, $params = array() ) {
1722 if ( $this->getTitle() ) {
1723 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1725 $this->setPageTitle( wfMsg( $title ) );
1726 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1727 $this->setRobotPolicy( 'noindex,nofollow' );
1728 $this->setArticleRelated( false );
1729 $this->enableClientCache( false );
1730 $this->mRedirect = '';
1731 $this->mBodytext = '';
1733 array_unshift( $params, 'parse' );
1734 array_unshift( $params, $msg );
1735 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1737 $this->returnToMain();
1741 * Output a standard permission error page
1743 * @param $errors Array: error message keys
1744 * @param $action String: action that was denied or null if unknown
1746 public function showPermissionsErrorPage( $errors, $action = null ) {
1747 $this->mDebugtext .= 'Original title: ' .
1748 $this->getTitle()->getPrefixedText() . "\n";
1749 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1750 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1751 $this->setRobotPolicy( 'noindex,nofollow' );
1752 $this->setArticleRelated( false );
1753 $this->enableClientCache( false );
1754 $this->mRedirect = '';
1755 $this->mBodytext = '';
1756 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1760 * Display an error page indicating that a given version of MediaWiki is
1761 * required to use it
1763 * @param $version Mixed: the version of MediaWiki needed to use the page
1765 public function versionRequired( $version ) {
1766 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1767 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1768 $this->setRobotPolicy( 'noindex,nofollow' );
1769 $this->setArticleRelated( false );
1770 $this->mBodytext = '';
1772 $this->addWikiMsg( 'versionrequiredtext', $version );
1773 $this->returnToMain();
1777 * Display an error page noting that a given permission bit is required.
1779 * @param $permission String: key required
1781 public function permissionRequired( $permission ) {
1782 global $wgLang;
1784 $this->setPageTitle( wfMsg( 'badaccess' ) );
1785 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1786 $this->setRobotPolicy( 'noindex,nofollow' );
1787 $this->setArticleRelated( false );
1788 $this->mBodytext = '';
1790 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1791 User::getGroupsWithPermission( $permission ) );
1792 if( $groups ) {
1793 $this->addWikiMsg(
1794 'badaccess-groups',
1795 $wgLang->commaList( $groups ),
1796 count( $groups )
1798 } else {
1799 $this->addWikiMsg( 'badaccess-group0' );
1801 $this->returnToMain();
1805 * Produce the stock "please login to use the wiki" page
1807 public function loginToUse() {
1808 global $wgUser;
1810 if( $wgUser->isLoggedIn() ) {
1811 $this->permissionRequired( 'read' );
1812 return;
1815 $skin = $wgUser->getSkin();
1817 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1818 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1819 $this->setRobotPolicy( 'noindex,nofollow' );
1820 $this->setArticleFlag( false );
1822 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1823 $loginLink = $skin->link(
1824 $loginTitle,
1825 wfMsgHtml( 'loginreqlink' ),
1826 array(),
1827 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1828 array( 'known', 'noclasses' )
1830 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1831 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1833 # Don't return to the main page if the user can't read it
1834 # otherwise we'll end up in a pointless loop
1835 $mainPage = Title::newMainPage();
1836 if( $mainPage->userCanRead() ) {
1837 $this->returnToMain( null, $mainPage );
1842 * Format a list of error messages
1844 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1845 * @param $action String: action that was denied or null if unknown
1846 * @return String: the wikitext error-messages, formatted into a list.
1848 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1849 if ( $action == null ) {
1850 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1851 } else {
1852 $action_desc = wfMsgNoTrans( "action-$action" );
1853 $text = wfMsgNoTrans(
1854 'permissionserrorstext-withaction',
1855 count( $errors ),
1856 $action_desc
1857 ) . "\n\n";
1860 if ( count( $errors ) > 1 ) {
1861 $text .= '<ul class="permissions-errors">' . "\n";
1863 foreach( $errors as $error ) {
1864 $text .= '<li>';
1865 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1866 $text .= "</li>\n";
1868 $text .= '</ul>';
1869 } else {
1870 $text .= "<div class=\"permissions-errors\">\n" .
1871 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
1872 "\n</div>";
1875 return $text;
1879 * Display a page stating that the Wiki is in read-only mode,
1880 * and optionally show the source of the page that the user
1881 * was trying to edit. Should only be called (for this
1882 * purpose) after wfReadOnly() has returned true.
1884 * For historical reasons, this function is _also_ used to
1885 * show the error message when a user tries to edit a page
1886 * they are not allowed to edit. (Unless it's because they're
1887 * blocked, then we show blockedPage() instead.) In this
1888 * case, the second parameter should be set to true and a list
1889 * of reasons supplied as the third parameter.
1891 * @todo Needs to be split into multiple functions.
1893 * @param $source String: source code to show (or null).
1894 * @param $protected Boolean: is this a permissions error?
1895 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1896 * @param $action String: action that was denied or null if unknown
1898 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1899 global $wgUser;
1900 $skin = $wgUser->getSkin();
1902 $this->setRobotPolicy( 'noindex,nofollow' );
1903 $this->setArticleRelated( false );
1905 // If no reason is given, just supply a default "I can't let you do
1906 // that, Dave" message. Should only occur if called by legacy code.
1907 if ( $protected && empty( $reasons ) ) {
1908 $reasons[] = array( 'badaccess-group0' );
1911 if ( !empty( $reasons ) ) {
1912 // Permissions error
1913 if( $source ) {
1914 $this->setPageTitle( wfMsg( 'viewsource' ) );
1915 $this->setSubtitle(
1916 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
1918 } else {
1919 $this->setPageTitle( wfMsg( 'badaccess' ) );
1921 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1922 } else {
1923 // Wiki is read only
1924 $this->setPageTitle( wfMsg( 'readonly' ) );
1925 $reason = wfReadOnlyReason();
1926 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
1929 // Show source, if supplied
1930 if( is_string( $source ) ) {
1931 $this->addWikiMsg( 'viewsourcetext' );
1933 $params = array(
1934 'id' => 'wpTextbox1',
1935 'name' => 'wpTextbox1',
1936 'cols' => $wgUser->getOption( 'cols' ),
1937 'rows' => $wgUser->getOption( 'rows' ),
1938 'readonly' => 'readonly'
1940 $this->addHTML( Html::element( 'textarea', $params, $source ) );
1942 // Show templates used by this article
1943 $skin = $wgUser->getSkin();
1944 $article = new Article( $this->getTitle() );
1945 $this->addHTML( "<div class='templatesUsed'>
1946 {$skin->formatTemplates( $article->getUsedTemplates() )}
1947 </div>
1948 " );
1951 # If the title doesn't exist, it's fairly pointless to print a return
1952 # link to it. After all, you just tried editing it and couldn't, so
1953 # what's there to do there?
1954 if( $this->getTitle()->exists() ) {
1955 $this->returnToMain( null, $this->getTitle() );
1960 * Adds JS-based password security checker
1961 * @param $passwordId String ID of input box containing password
1962 * @param $retypeId String ID of input box containing retyped password
1963 * @return none
1965 public function addPasswordSecurity( $passwordId, $retypeId ) {
1966 $this->includeJQuery();
1967 $data = array(
1968 'password' => '#' . $passwordId,
1969 'retype' => '#' . $retypeId,
1970 'messages' => array(),
1972 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
1973 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
1974 ) as $message ) {
1975 $data['messages'][$message] = wfMsg( $message );
1977 $this->addScript( Html::inlineScript( 'var passwordSecurity=' . FormatJson::encode( $data ) ) );
1978 $this->addScriptFile( 'password.js' );
1979 $this->addStyle( 'common/password.css' );
1982 /** @deprecated */
1983 public function errorpage( $title, $msg ) {
1984 wfDeprecated( __METHOD__ );
1985 throw new ErrorPageError( $title, $msg );
1988 /** @deprecated */
1989 public function databaseError( $fname, $sql, $error, $errno ) {
1990 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1993 /** @deprecated */
1994 public function fatalError( $message ) {
1995 wfDeprecated( __METHOD__ );
1996 throw new FatalError( $message );
1999 /** @deprecated */
2000 public function unexpectedValueError( $name, $val ) {
2001 wfDeprecated( __METHOD__ );
2002 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
2005 /** @deprecated */
2006 public function fileCopyError( $old, $new ) {
2007 wfDeprecated( __METHOD__ );
2008 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
2011 /** @deprecated */
2012 public function fileRenameError( $old, $new ) {
2013 wfDeprecated( __METHOD__ );
2014 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
2017 /** @deprecated */
2018 public function fileDeleteError( $name ) {
2019 wfDeprecated( __METHOD__ );
2020 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
2023 /** @deprecated */
2024 public function fileNotFoundError( $name ) {
2025 wfDeprecated( __METHOD__ );
2026 throw new FatalError( wfMsg( 'filenotfound', $name ) );
2029 public function showFatalError( $message ) {
2030 $this->setPageTitle( wfMsg( 'internalerror' ) );
2031 $this->setRobotPolicy( 'noindex,nofollow' );
2032 $this->setArticleRelated( false );
2033 $this->enableClientCache( false );
2034 $this->mRedirect = '';
2035 $this->mBodytext = $message;
2038 public function showUnexpectedValueError( $name, $val ) {
2039 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2042 public function showFileCopyError( $old, $new ) {
2043 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2046 public function showFileRenameError( $old, $new ) {
2047 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2050 public function showFileDeleteError( $name ) {
2051 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2054 public function showFileNotFoundError( $name ) {
2055 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2059 * Add a "return to" link pointing to a specified title
2061 * @param $title Title to link
2062 * @param $query String: query string
2063 * @param $text String text of the link (input is not escaped)
2065 public function addReturnTo( $title, $query = array(), $text = null ) {
2066 global $wgUser;
2067 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2068 $link = wfMsgHtml(
2069 'returnto',
2070 $wgUser->getSkin()->link( $title, $text, array(), $query )
2072 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2076 * Add a "return to" link pointing to a specified title,
2077 * or the title indicated in the request, or else the main page
2079 * @param $unused No longer used
2080 * @param $returnto Title or String to return to
2081 * @param $returntoquery String: query string for the return to link
2083 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2084 global $wgRequest;
2086 if ( $returnto == null ) {
2087 $returnto = $wgRequest->getText( 'returnto' );
2090 if ( $returntoquery == null ) {
2091 $returntoquery = $wgRequest->getText( 'returntoquery' );
2094 if ( $returnto === '' ) {
2095 $returnto = Title::newMainPage();
2098 if ( is_object( $returnto ) ) {
2099 $titleObj = $returnto;
2100 } else {
2101 $titleObj = Title::newFromText( $returnto );
2103 if ( !is_object( $titleObj ) ) {
2104 $titleObj = Title::newMainPage();
2107 $this->addReturnTo( $titleObj, $returntoquery );
2111 * @param $sk Skin The given Skin
2112 * @param $includeStyle Boolean: unused
2113 * @return String: The doctype, opening <html>, and head element.
2115 public function headElement( Skin $sk, $includeStyle = true ) {
2116 global $wgOutputEncoding, $wgMimeType;
2117 global $wgUseTrackbacks, $wgHtml5;
2118 global $wgUser, $wgRequest, $wgLang;
2120 if ( $sk->commonPrintStylesheet() ) {
2121 $this->addStyle( 'common/wikiprintable.css', 'print' );
2123 $sk->setupUserCss( $this );
2125 $ret = Html::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2127 if ( $this->getHTMLTitle() == '' ) {
2128 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2131 $openHead = Html::openElement( 'head' );
2132 if ( $openHead ) {
2133 # Don't bother with the newline if $head == ''
2134 $ret .= "$openHead\n";
2137 if ( $wgHtml5 ) {
2138 # More succinct than <meta http-equiv=Content-Type>, has the
2139 # same effect
2140 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2141 } else {
2142 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2145 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2147 $ret .= implode( "\n", array(
2148 $this->getHeadLinks(),
2149 $this->buildCssLinks(),
2150 $this->getHeadScripts( $sk ) . $this->getHeadItems(),
2151 ) );
2152 if ( $sk->usercss ) {
2153 $ret .= Html::inlineStyle( $sk->usercss );
2156 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2157 $ret .= $this->getTitle()->trackbackRDF();
2160 $closeHead = Html::closeElement( 'head' );
2161 if ( $closeHead ) {
2162 $ret .= "$closeHead\n";
2165 $bodyAttrs = array();
2167 # Crazy edit-on-double-click stuff
2168 $action = $wgRequest->getVal( 'action', 'view' );
2170 if (
2171 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2172 !in_array( $action, array( 'edit', 'submit' ) ) &&
2173 $wgUser->getOption( 'editondblclick' )
2176 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2179 # Class bloat
2180 $dir = wfUILang()->getDir();
2181 $bodyAttrs['class'] = "mediawiki $dir";
2183 if ( $wgLang->capitalizeAllNouns() ) {
2184 # A <body> class is probably not the best way to do this . . .
2185 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2187 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2188 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2189 $bodyAttrs['class'] .= ' ns-special';
2190 } elseif ( $this->getTitle()->isTalkPage() ) {
2191 $bodyAttrs['class'] .= ' ns-talk';
2192 } else {
2193 $bodyAttrs['class'] .= ' ns-subject';
2195 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2196 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2198 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2200 return $ret;
2204 * Gets the global variables and mScripts; also adds userjs to the end if
2205 * enabled
2207 * @param $sk Skin object to use
2208 * @return String: HTML fragment
2210 function getHeadScripts( Skin $sk ) {
2211 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
2212 global $wgStylePath, $wgStyleVersion;
2214 $scripts = Skin::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2215 $scripts .= Html::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
2217 // add site JS if enabled
2218 if( $wgUseSiteJs ) {
2219 $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
2220 $this->addScriptFile(
2221 Skin::makeUrl(
2222 '-',
2223 "action=raw$jsCache&gen=js&useskin=" .
2224 urlencode( $sk->getSkinName() )
2229 // add user JS if enabled
2230 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2231 $action = $wgRequest->getVal( 'action', 'view' );
2232 if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2233 # XXX: additional security check/prompt?
2234 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2235 } else {
2236 $userpage = $wgUser->getUserPage();
2237 $names = array( 'common', $sk->getSkinName() );
2238 foreach( $names as $name ) {
2239 $scriptpage = Title::makeTitleSafe(
2240 NS_USER,
2241 $userpage->getDBkey() . '/' . $name . '.js'
2243 if ( $scriptpage && $scriptpage->exists() && ( $scriptpage->getLength() > 0 ) ) {
2244 $userjs = $scriptpage->getLocalURL( 'action=raw&ctype=' . $wgJsMimeType );
2245 $this->addScriptFile( $userjs, $scriptpage->getLatestRevID() );
2251 $scripts .= "\n" . $this->mScripts;
2252 return $scripts;
2256 * Add default \<meta\> tags
2258 protected function addDefaultMeta() {
2259 global $wgVersion, $wgHtml5;
2261 static $called = false;
2262 if ( $called ) {
2263 # Don't run this twice
2264 return;
2266 $called = true;
2268 if ( !$wgHtml5 ) {
2269 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2271 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2273 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2274 if( $p !== 'index,follow' ) {
2275 // http://www.robotstxt.org/wc/meta-user.html
2276 // Only show if it's different from the default robots policy
2277 $this->addMeta( 'robots', $p );
2280 if ( count( $this->mKeywords ) > 0 ) {
2281 $strip = array(
2282 "/<.*?" . ">/" => '',
2283 "/_/" => ' '
2285 $this->addMeta(
2286 'keywords',
2287 preg_replace(
2288 array_keys( $strip ),
2289 array_values( $strip ),
2290 implode( ',', $this->mKeywords )
2297 * @return string HTML tag links to be put in the header.
2299 public function getHeadLinks() {
2300 global $wgFeed;
2302 // Ideally this should happen earlier, somewhere. :P
2303 $this->addDefaultMeta();
2305 $tags = array();
2307 foreach ( $this->mMetatags as $tag ) {
2308 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2309 $a = 'http-equiv';
2310 $tag[0] = substr( $tag[0], 5 );
2311 } else {
2312 $a = 'name';
2314 $tags[] = Html::element( 'meta',
2315 array(
2316 $a => $tag[0],
2317 'content' => $tag[1]
2321 foreach ( $this->mLinktags as $tag ) {
2322 $tags[] = Html::element( 'link', $tag );
2325 if( $wgFeed ) {
2326 foreach( $this->getSyndicationLinks() as $format => $link ) {
2327 # Use the page name for the title (accessed through $wgTitle since
2328 # there's no other way). In principle, this could lead to issues
2329 # with having the same name for different feeds corresponding to
2330 # the same page, but we can't avoid that at this low a level.
2332 $tags[] = $this->feedLink(
2333 $format,
2334 $link,
2335 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2336 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2340 # Recent changes feed should appear on every page (except recentchanges,
2341 # that would be redundant). Put it after the per-page feed to avoid
2342 # changing existing behavior. It's still available, probably via a
2343 # menu in your browser. Some sites might have a different feed they'd
2344 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2345 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2346 # If so, use it instead.
2348 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2349 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2351 if ( $wgOverrideSiteFeed ) {
2352 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2353 $tags[] = $this->feedLink(
2354 $type,
2355 htmlspecialchars( $feedUrl ),
2356 wfMsg( "site-{$type}-feed", $wgSitename )
2359 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2360 foreach ( $wgAdvertisedFeedTypes as $format ) {
2361 $tags[] = $this->feedLink(
2362 $format,
2363 $rctitle->getLocalURL( "feed={$format}" ),
2364 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2370 return implode( "\n", $tags );
2374 * Generate a <link rel/> for a feed.
2376 * @param $type String: feed type
2377 * @param $url String: URL to the feed
2378 * @param $text String: value of the "title" attribute
2379 * @return String: HTML fragment
2381 private function feedLink( $type, $url, $text ) {
2382 return Html::element( 'link', array(
2383 'rel' => 'alternate',
2384 'type' => "application/$type+xml",
2385 'title' => $text,
2386 'href' => $url )
2391 * Add a local or specified stylesheet, with the given media options.
2392 * Meant primarily for internal use...
2394 * @param $style String: URL to the file
2395 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2396 * @param $condition String: for IE conditional comments, specifying an IE version
2397 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2399 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2400 $options = array();
2401 // Even though we expect the media type to be lowercase, but here we
2402 // force it to lowercase to be safe.
2403 if( $media ) {
2404 $options['media'] = $media;
2406 if( $condition ) {
2407 $options['condition'] = $condition;
2409 if( $dir ) {
2410 $options['dir'] = $dir;
2412 $this->styles[$style] = $options;
2416 * Adds inline CSS styles
2417 * @param $style_css Mixed: inline CSS
2419 public function addInlineStyle( $style_css ){
2420 $this->mScripts .= Html::inlineStyle( $style_css );
2424 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2425 * These will be applied to various media & IE conditionals.
2427 public function buildCssLinks() {
2428 return implode( "\n", $this->buildCssLinksArray() );
2431 public function buildCssLinksArray() {
2432 $links = array();
2433 foreach( $this->styles as $file => $options ) {
2434 $link = $this->styleLink( $file, $options );
2435 if( $link ) {
2436 $links[$file] = $link;
2439 return $links;
2443 * Generate \<link\> tags for stylesheets
2445 * @param $style String: URL to the file
2446 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2447 * keys
2448 * @return String: HTML fragment
2450 protected function styleLink( $style, $options ) {
2451 if( isset( $options['dir'] ) ) {
2452 $siteDir = wfUILang()->getDir();
2453 if( $siteDir != $options['dir'] ) {
2454 return '';
2458 if( isset( $options['media'] ) ) {
2459 $media = $this->transformCssMedia( $options['media'] );
2460 if( is_null( $media ) ) {
2461 return '';
2463 } else {
2464 $media = 'all';
2467 if( substr( $style, 0, 1 ) == '/' ||
2468 substr( $style, 0, 5 ) == 'http:' ||
2469 substr( $style, 0, 6 ) == 'https:' ) {
2470 $url = $style;
2471 } else {
2472 global $wgStylePath, $wgStyleVersion;
2473 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2476 $link = Html::linkedStyle( $url, $media );
2478 if( isset( $options['condition'] ) ) {
2479 $condition = htmlspecialchars( $options['condition'] );
2480 $link = "<!--[if $condition]>$link<![endif]-->";
2482 return $link;
2486 * Transform "media" attribute based on request parameters
2488 * @param $media String: current value of the "media" attribute
2489 * @return String: modified value of the "media" attribute
2491 function transformCssMedia( $media ) {
2492 global $wgRequest, $wgHandheldForIPhone;
2494 // Switch in on-screen display for media testing
2495 $switches = array(
2496 'printable' => 'print',
2497 'handheld' => 'handheld',
2499 foreach( $switches as $switch => $targetMedia ) {
2500 if( $wgRequest->getBool( $switch ) ) {
2501 if( $media == $targetMedia ) {
2502 $media = '';
2503 } elseif( $media == 'screen' ) {
2504 return null;
2509 // Expand longer media queries as iPhone doesn't grok 'handheld'
2510 if( $wgHandheldForIPhone ) {
2511 $mediaAliases = array(
2512 'screen' => 'screen and (min-device-width: 481px)',
2513 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2516 if( isset( $mediaAliases[$media] ) ) {
2517 $media = $mediaAliases[$media];
2521 return $media;
2525 * Turn off regular page output and return an error reponse
2526 * for when rate limiting has triggered.
2528 public function rateLimited() {
2529 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2530 $this->setRobotPolicy( 'noindex,follow' );
2531 $this->setArticleRelated( false );
2532 $this->enableClientCache( false );
2533 $this->mRedirect = '';
2534 $this->clearHTML();
2535 $this->setStatusCode( 503 );
2536 $this->addWikiMsg( 'actionthrottledtext' );
2538 $this->returnToMain( null, $this->getTitle() );
2542 * Show a warning about slave lag
2544 * If the lag is higher than $wgSlaveLagCritical seconds,
2545 * then the warning is a bit more obvious. If the lag is
2546 * lower than $wgSlaveLagWarning, then no warning is shown.
2548 * @param $lag Integer: slave lag
2550 public function showLagWarning( $lag ) {
2551 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2552 if( $lag >= $wgSlaveLagWarning ) {
2553 $message = $lag < $wgSlaveLagCritical
2554 ? 'lag-warn-normal'
2555 : 'lag-warn-high';
2556 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2557 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2562 * Add a wikitext-formatted message to the output.
2563 * This is equivalent to:
2565 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2567 public function addWikiMsg( /*...*/ ) {
2568 $args = func_get_args();
2569 $name = array_shift( $args );
2570 $this->addWikiMsgArray( $name, $args );
2574 * Add a wikitext-formatted message to the output.
2575 * Like addWikiMsg() except the parameters are taken as an array
2576 * instead of a variable argument list.
2578 * $options is passed through to wfMsgExt(), see that function for details.
2580 public function addWikiMsgArray( $name, $args, $options = array() ) {
2581 $options[] = 'parse';
2582 $text = wfMsgExt( $name, $options, $args );
2583 $this->addHTML( $text );
2587 * This function takes a number of message/argument specifications, wraps them in
2588 * some overall structure, and then parses the result and adds it to the output.
2590 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2591 * on. The subsequent arguments may either be strings, in which case they are the
2592 * message names, or arrays, in which case the first element is the message name,
2593 * and subsequent elements are the parameters to that message.
2595 * The special named parameter 'options' in a message specification array is passed
2596 * through to the $options parameter of wfMsgExt().
2598 * Don't use this for messages that are not in users interface language.
2600 * For example:
2602 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2604 * Is equivalent to:
2606 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2608 * The newline after opening div is needed in some wikitext. See bug 19226.
2610 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2611 $msgSpecs = func_get_args();
2612 array_shift( $msgSpecs );
2613 $msgSpecs = array_values( $msgSpecs );
2614 $s = $wrap;
2615 foreach ( $msgSpecs as $n => $spec ) {
2616 $options = array();
2617 if ( is_array( $spec ) ) {
2618 $args = $spec;
2619 $name = array_shift( $args );
2620 if ( isset( $args['options'] ) ) {
2621 $options = $args['options'];
2622 unset( $args['options'] );
2624 } else {
2625 $args = array();
2626 $name = $spec;
2628 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2630 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2634 * Include jQuery core. Use this to avoid loading it multiple times
2635 * before we get a usable script loader.
2637 * @param $modules Array: list of jQuery modules which should be loaded
2638 * @return Array: the list of modules which were not loaded.
2639 * @since 1.16
2641 public function includeJQuery( $modules = array() ) {
2642 global $wgStylePath, $wgStyleVersion, $wgJQueryVersion, $wgJQueryMinified;
2644 $supportedModules = array( /** TODO: add things here */ );
2645 $unsupported = array_diff( $modules, $supportedModules );
2647 $min = $wgJQueryMinified ? '.min' : '';
2648 $url = "$wgStylePath/common/jquery-$wgJQueryVersion$min.js?$wgStyleVersion";
2649 if ( !$this->mJQueryDone ) {
2650 $this->mJQueryDone = true;
2651 $this->mScripts = Html::linkedScript( $url ) . "\n" . $this->mScripts;
2653 return $unsupported;