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 = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
27 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
28 var $mInlineMsg = array();
30 var $mTemplateIds = array();
33 var $mSuppressQuickbar = false;
34 var $mDoNothing = false;
35 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
36 var $mIsArticleRelated = true;
37 protected $mParserOptions = null; // lazy initialised, use parserOptions()
39 var $mFeedLinks = array();
41 var $mEnableClientCache = true;
42 var $mArticleBodyOnly = false;
44 var $mNewSectionLink = false;
45 var $mHideNewSectionLink = false;
46 var $mNoGallery = false;
47 var $mPageTitleActionText = '';
48 var $mParseWarnings = array();
49 var $mSquidMaxage = 0;
50 var $mRevisionId = null;
51 protected $mTitle = null;
54 * An array of stylesheet filenames (relative from skins path), with options
55 * for CSS media, IE conditions, and RTL/LTR direction.
56 * For internal use; add settings in the skin via $this->addStyle()
58 var $styles = array();
61 * Whether to load jQuery core.
63 protected $mJQueryDone = false;
65 private $mIndexPolicy = 'index';
66 private $mFollowPolicy = 'follow';
67 private $mVaryHeader = array(
68 'Accept-Encoding' => array( 'list-contains=gzip' ),
74 * Initialise private variables
76 function __construct() {
77 global $wgAllowUserJs;
78 $this->mAllowUserJs
= $wgAllowUserJs;
82 * Redirect to $url rather than displaying the normal page
84 * @param $url String: URL
85 * @param $responsecode String: HTTP status code
87 public function redirect( $url, $responsecode = '302' ) {
88 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
89 $this->mRedirect
= str_replace( "\n", '', $url );
90 $this->mRedirectCode
= $responsecode;
94 * Get the URL to redirect to, or an empty string if not redirect URL set
98 public function getRedirect() {
99 return $this->mRedirect
;
103 * Set the HTTP status code to send with the output.
105 * @param $statusCode Integer
108 public function setStatusCode( $statusCode ) {
109 $this->mStatusCode
= $statusCode;
113 * Add a new <meta> tag
114 * To add an http-equiv meta tag, precede the name with "http:"
116 * @param $name tag name
117 * @param $val tag value
119 function addMeta( $name, $val ) {
120 array_push( $this->mMetatags
, array( $name, $val ) );
124 * Add a keyword or a list of keywords in the page header
126 * @param $text String or array of strings
128 function addKeyword( $text ) {
129 if( is_array( $text ) ) {
130 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
132 array_push( $this->mKeywords
, $text );
137 * Add a new \<link\> tag to the page header
139 * @param $linkarr Array: associative array of attributes.
141 function addLink( $linkarr ) {
142 array_push( $this->mLinktags
, $linkarr );
146 * Add a new \<link\> with "rel" attribute set to "meta"
148 * @param $linkarr Array: associative array mapping attribute names to their
149 * values, both keys and values will be escaped, and the
150 * "rel" attribute will be automatically added
152 function addMetadataLink( $linkarr ) {
153 # note: buggy CC software only reads first "meta" link
154 static $haveMeta = false;
155 $linkarr['rel'] = $haveMeta ?
'alternate meta' : 'meta';
156 $this->addLink( $linkarr );
161 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
163 * @param $script String: raw HTML
165 function addScript( $script ) {
166 $this->mScripts
.= $script . "\n";
170 * Register and add a stylesheet from an extension directory.
172 * @param $url String path to sheet. Provide either a full url (beginning
173 * with 'http', etc) or a relative path from the document root
174 * (beginning with '/'). Otherwise it behaves identically to
175 * addStyle() and draws from the /skins folder.
177 public function addExtensionStyle( $url ) {
178 array_push( $this->mExtStyles
, $url );
182 * Get all links added by extensions
186 function getExtStyle() {
187 return $this->mExtStyles
;
191 * Add a JavaScript file out of skins/common, or a given relative path.
193 * @param $file String: filename in skins/common or complete on-server path
195 * @param $version String: style version of the file. Defaults to $wgStyleVersion
197 public function addScriptFile( $file, $version = null ) {
198 global $wgStylePath, $wgStyleVersion;
199 // See if $file parameter is an absolute URL or begins with a slash
200 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
203 $path = "{$wgStylePath}/common/{$file}";
205 if ( is_null( $version ) )
206 $version = $wgStyleVersion;
207 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
211 * Add a self-contained script tag with the given contents
213 * @param $script String: JavaScript text, no <script> tags
215 public function addInlineScript( $script ) {
216 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
220 * Get all registered JS and CSS tags for the header.
224 function getScript() {
225 return $this->mScripts
. $this->getHeadItems();
229 * Get the list of modules to include on this page
231 * @return Array of module names
233 public function getModules() {
234 return $this->mModules
;
238 * Add one or more modules recognized by the resource loader. Modules added
239 * through this function will be loaded by the resource loader when the
242 * @param $modules Mixed: module name (string) or array of module names
244 public function addModules( $modules ) {
245 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
249 * Get the list of module JS to include on this page
250 * @return array of module names
252 public function getModuleScripts() {
253 return $this->mModuleScripts
;
257 * Add only JS of one or more modules recognized by the resource loader. Module
258 * scripts added through this function will be loaded by the resource loader when
261 * @param $modules Mixed: module name (string) or array of module names
263 public function addModuleScripts( $modules ) {
264 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
268 * Get the list of module CSS to include on this page
270 * @return Array of module names
272 public function getModuleStyles() {
273 return $this->mModuleStyles
;
277 * Add only CSS of one or more modules recognized by the resource loader. Module
278 * styles added through this function will be loaded by the resource loader when
281 * @param $modules Mixed: module name (string) or array of module names
283 public function addModuleStyles( $modules ) {
284 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
288 * Get the list of module messages to include on this page
290 * @return Array of module names
292 public function getModuleMessages() {
293 return $this->mModuleMessages
;
297 * Add only messages of one or more modules recognized by the resource loader.
298 * Module messages added through this function will be loaded by the resource
299 * loader when the page loads.
301 * @param $modules Mixed: module name (string) or array of module names
303 public function addModuleMessages( $modules ) {
304 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
308 * Get all header items in a string
312 function getHeadItems() {
314 foreach ( $this->mHeadItems
as $item ) {
321 * Add or replace an header item to the output
323 * @param $name String: item name
324 * @param $value String: raw HTML
326 public function addHeadItem( $name, $value ) {
327 $this->mHeadItems
[$name] = $value;
331 * Check if the header item $name is already set
333 * @param $name String: item name
336 public function hasHeadItem( $name ) {
337 return isset( $this->mHeadItems
[$name] );
341 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
343 * @param $tag String: value of "ETag" header
345 function setETag( $tag ) {
350 * Set whether the output should only contain the body of the article,
351 * without any skin, sidebar, etc.
352 * Used e.g. when calling with "action=render".
354 * @param $only Boolean: whether to output only the body of the article
356 public function setArticleBodyOnly( $only ) {
357 $this->mArticleBodyOnly
= $only;
361 * Return whether the output will contain only the body of the article
365 public function getArticleBodyOnly() {
366 return $this->mArticleBodyOnly
;
370 * checkLastModified tells the client to use the client-cached page if
371 * possible. If sucessful, the OutputPage is disabled so that
372 * any future call to OutputPage->output() have no effect.
374 * Side effect: sets mLastModified for Last-Modified header
376 * @return Boolean: true iff cache-ok headers was sent.
378 public function checkLastModified( $timestamp ) {
379 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
381 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
382 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
385 if( !$wgCachePages ) {
386 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
389 if( $wgUser->getOption( 'nocache' ) ) {
390 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
394 $timestamp = wfTimestamp( TS_MW
, $timestamp );
395 $modifiedTimes = array(
396 'page' => $timestamp,
397 'user' => $wgUser->getTouched(),
398 'epoch' => $wgCacheEpoch
400 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
402 $maxModified = max( $modifiedTimes );
403 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
405 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
406 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
412 foreach ( $modifiedTimes as $name => $value ) {
413 if ( $info !== '' ) {
416 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
419 # IE sends sizes after the date like this:
420 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
421 # this breaks strtotime().
422 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
424 wfSuppressWarnings(); // E_STRICT system time bitching
425 $clientHeaderTime = strtotime( $clientHeader );
427 if ( !$clientHeaderTime ) {
428 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
431 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
433 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
434 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
435 wfDebug( __METHOD__
. ": effective Last-Modified: " .
436 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
437 if( $clientHeaderTime < $maxModified ) {
438 wfDebug( __METHOD__
. ": STALE, $info\n", false );
443 # Give a 304 response code and disable body output
444 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
445 ini_set( 'zlib.output_compression', 0 );
446 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
447 $this->sendCacheControl();
450 // Don't output a compressed blob when using ob_gzhandler;
451 // it's technically against HTTP spec and seems to confuse
452 // Firefox when the response gets split over two packets.
453 wfClearOutputBuffers();
459 * Override the last modified timestamp
461 * @param $timestamp String: new timestamp, in a format readable by
464 public function setLastModified( $timestamp ) {
465 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
469 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
471 * @param $policy String: the literal string to output as the contents of
472 * the meta tag. Will be parsed according to the spec and output in
476 public function setRobotPolicy( $policy ) {
477 $policy = Article
::formatRobotPolicy( $policy );
479 if( isset( $policy['index'] ) ) {
480 $this->setIndexPolicy( $policy['index'] );
482 if( isset( $policy['follow'] ) ) {
483 $this->setFollowPolicy( $policy['follow'] );
488 * Set the index policy for the page, but leave the follow policy un-
491 * @param $policy string Either 'index' or 'noindex'.
494 public function setIndexPolicy( $policy ) {
495 $policy = trim( $policy );
496 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
497 $this->mIndexPolicy
= $policy;
502 * Set the follow policy for the page, but leave the index policy un-
505 * @param $policy String: either 'follow' or 'nofollow'.
508 public function setFollowPolicy( $policy ) {
509 $policy = trim( $policy );
510 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
511 $this->mFollowPolicy
= $policy;
516 * Set the new value of the "action text", this will be added to the
517 * "HTML title", separated from it with " - ".
519 * @param $text String: new value of the "action text"
521 public function setPageTitleActionText( $text ) {
522 $this->mPageTitleActionText
= $text;
526 * Get the value of the "action text"
530 public function getPageTitleActionText() {
531 if ( isset( $this->mPageTitleActionText
) ) {
532 return $this->mPageTitleActionText
;
537 * "HTML title" means the contents of <title>.
538 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
540 public function setHTMLTitle( $name ) {
541 $this->mHTMLtitle
= $name;
545 * Return the "HTML title", i.e. the content of the <title> tag.
549 public function getHTMLTitle() {
550 return $this->mHTMLtitle
;
554 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
555 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
556 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
557 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
559 public function setPageTitle( $name ) {
560 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
561 # but leave "<i>foobar</i>" alone
562 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
563 $this->mPagetitle
= $nameWithTags;
565 $taction = $this->getPageTitleActionText();
566 if( !empty( $taction ) ) {
567 $name .= ' - '.$taction;
570 # change "<i>foo&bar</i>" to "foo&bar"
571 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
575 * Return the "page title", i.e. the content of the \<h1\> tag.
579 public function getPageTitle() {
580 return $this->mPagetitle
;
584 * Set the Title object to use
586 * @param $t Title object
588 public function setTitle( $t ) {
593 * Get the Title object used in this instance
597 public function getTitle() {
598 if ( $this->mTitle
instanceof Title
) {
599 return $this->mTitle
;
601 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
608 * Replace the subtile with $str
610 * @param $str String: new value of the subtitle
612 public function setSubtitle( $str ) {
613 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
617 * Add $str to the subtitle
619 * @param $str String to add to the subtitle
621 public function appendSubtitle( $str ) {
622 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
630 public function getSubtitle() {
631 return $this->mSubtitle
;
635 * Set the page as printable, i.e. it'll be displayed with with all
636 * print styles included
638 public function setPrintable() {
639 $this->mPrintable
= true;
643 * Return whether the page is "printable"
647 public function isPrintable() {
648 return $this->mPrintable
;
652 * Disable output completely, i.e. calling output() will have no effect
654 public function disable() {
655 $this->mDoNothing
= true;
659 * Return whether the output will be completely disabled
663 public function isDisabled() {
664 return $this->mDoNothing
;
668 * Show an "add new section" link?
672 public function showNewSectionLink() {
673 return $this->mNewSectionLink
;
677 * Forcibly hide the new section link?
681 public function forceHideNewSectionLink() {
682 return $this->mHideNewSectionLink
;
686 * Add or remove feed links in the page header
687 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
688 * for the new version
691 * @param $show Boolean: true: add default feeds, false: remove all feeds
693 public function setSyndicated( $show = true ) {
695 $this->setFeedAppendQuery( false );
697 $this->mFeedLinks
= array();
702 * Add default feeds to the page header
703 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
704 * for the new version
707 * @param $val String: query to append to feed links or false to output
710 public function setFeedAppendQuery( $val ) {
711 global $wgAdvertisedFeedTypes;
713 $this->mFeedLinks
= array();
715 foreach ( $wgAdvertisedFeedTypes as $type ) {
716 $query = "feed=$type";
717 if ( is_string( $val ) ) {
718 $query .= '&' . $val;
720 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
725 * Add a feed link to the page header
727 * @param $format String: feed type, should be a key of $wgFeedClasses
728 * @param $href String: URL
730 public function addFeedLink( $format, $href ) {
731 global $wgAdvertisedFeedTypes;
733 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
734 $this->mFeedLinks
[$format] = $href;
739 * Should we output feed links for this page?
742 public function isSyndicated() {
743 return count( $this->mFeedLinks
) > 0;
747 * Return URLs for each supported syndication format for this page.
748 * @return array associating format keys with URLs
750 public function getSyndicationLinks() {
751 return $this->mFeedLinks
;
755 * Will currently always return null
759 public function getFeedAppendQuery() {
760 return $this->mFeedLinksAppendQuery
;
764 * Set whether the displayed content is related to the source of the
765 * corresponding article on the wiki
766 * Setting true will cause the change "article related" toggle to true
770 public function setArticleFlag( $v ) {
771 $this->mIsarticle
= $v;
773 $this->mIsArticleRelated
= $v;
778 * Return whether the content displayed page is related to the source of
779 * the corresponding article on the wiki
783 public function isArticle() {
784 return $this->mIsarticle
;
788 * Set whether this page is related an article on the wiki
789 * Setting false will cause the change of "article flag" toggle to false
793 public function setArticleRelated( $v ) {
794 $this->mIsArticleRelated
= $v;
796 $this->mIsarticle
= false;
801 * Return whether this page is related an article on the wiki
805 public function isArticleRelated() {
806 return $this->mIsArticleRelated
;
810 * Add new language links
812 * @param $newLinkArray Associative array mapping language code to the page
815 public function addLanguageLinks( $newLinkArray ) {
816 $this->mLanguageLinks +
= $newLinkArray;
820 * Reset the language links and add new language links
822 * @param $newLinkArray Associative array mapping language code to the page
825 public function setLanguageLinks( $newLinkArray ) {
826 $this->mLanguageLinks
= $newLinkArray;
830 * Get the list of language links
832 * @return Associative array mapping language code to the page name
834 public function getLanguageLinks() {
835 return $this->mLanguageLinks
;
839 * Add an array of categories, with names in the keys
841 * @param $categories Associative array mapping category name to its sort key
843 public function addCategoryLinks( $categories ) {
844 global $wgUser, $wgContLang;
846 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
850 # Add the links to a LinkBatch
851 $arr = array( NS_CATEGORY
=> $categories );
853 $lb->setArray( $arr );
855 # Fetch existence plus the hiddencat property
856 $dbr = wfGetDB( DB_SLAVE
);
857 $pageTable = $dbr->tableName( 'page' );
858 $where = $lb->constructSet( 'page', $dbr );
859 $propsTable = $dbr->tableName( 'page_props' );
860 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
861 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
862 $res = $dbr->query( $sql, __METHOD__
);
864 # Add the results to the link cache
865 $lb->addResultToCache( LinkCache
::singleton(), $res );
867 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
868 $categories = array_combine(
869 array_keys( $categories ),
870 array_fill( 0, count( $categories ), 'normal' )
873 # Mark hidden categories
874 foreach ( $res as $row ) {
875 if ( isset( $row->pp_value
) ) {
876 $categories[$row->page_title
] = 'hidden';
880 # Add the remaining categories to the skin
881 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
882 $sk = $wgUser->getSkin();
883 foreach ( $categories as $category => $type ) {
884 $origcategory = $category;
885 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
886 $wgContLang->findVariantLink( $category, $title, true );
887 if ( $category != $origcategory ) {
888 if ( array_key_exists( $category, $categories ) ) {
892 $text = $wgContLang->convertHtml( $title->getText() );
893 $this->mCategories
[] = $title->getText();
894 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
900 * Reset the category links (but not the category list) and add $categories
902 * @param $categories Associative array mapping category name to its sort key
904 public function setCategoryLinks( $categories ) {
905 $this->mCategoryLinks
= array();
906 $this->addCategoryLinks( $categories );
910 * Get the list of category links, in a 2-D array with the following format:
911 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
912 * hidden categories) and $link a HTML fragment with a link to the category
917 public function getCategoryLinks() {
918 return $this->mCategoryLinks
;
922 * Get the list of category names this page belongs to
924 * @return Array of strings
926 public function getCategories() {
927 return $this->mCategories
;
931 * Suppress the quickbar from the output, only for skin supporting
934 public function suppressQuickbar() {
935 $this->mSuppressQuickbar
= true;
939 * Return whether the quickbar should be suppressed from the output
943 public function isQuickbarSuppressed() {
944 return $this->mSuppressQuickbar
;
948 * Remove user JavaScript from scripts to load
950 public function disallowUserJs() {
951 $this->mAllowUserJs
= false;
955 * Return whether user JavaScript is allowed for this page
959 public function isUserJsAllowed() {
960 return $this->mAllowUserJs
;
964 * Prepend $text to the body HTML
966 * @param $text String: HTML
968 public function prependHTML( $text ) {
969 $this->mBodytext
= $text . $this->mBodytext
;
973 * Append $text to the body HTML
975 * @param $text String: HTML
977 public function addHTML( $text ) {
978 $this->mBodytext
.= $text;
982 * Clear the body HTML
984 public function clearHTML() {
985 $this->mBodytext
= '';
991 * @return String: HTML
993 public function getHTML() {
994 return $this->mBodytext
;
998 * Add $text to the debug output
1000 * @param $text String: debug text
1002 public function debug( $text ) {
1003 $this->mDebugtext
.= $text;
1007 * @deprecated use parserOptions() instead
1009 public function setParserOptions( $options ) {
1010 wfDeprecated( __METHOD__
);
1011 return $this->parserOptions( $options );
1015 * Get/set the ParserOptions object to use for wikitext parsing
1017 * @param $options either the ParserOption to use or null to only get the
1018 * current ParserOption object
1019 * @return current ParserOption object
1021 public function parserOptions( $options = null ) {
1022 if ( !$this->mParserOptions
) {
1023 $this->mParserOptions
= new ParserOptions
;
1025 return wfSetVar( $this->mParserOptions
, $options );
1029 * Set the revision ID which will be seen by the wiki text parser
1030 * for things such as embedded {{REVISIONID}} variable use.
1032 * @param $revid Mixed: an positive integer, or null
1033 * @return Mixed: previous value
1035 public function setRevisionId( $revid ) {
1036 $val = is_null( $revid ) ?
null : intval( $revid );
1037 return wfSetVar( $this->mRevisionId
, $val );
1041 * Get the current revision ID
1045 public function getRevisionId() {
1046 return $this->mRevisionId
;
1050 * Convert wikitext to HTML and add it to the buffer
1051 * Default assumes that the current page title will be used.
1053 * @param $text String
1054 * @param $linestart Boolean: is this the start of a line?
1056 public function addWikiText( $text, $linestart = true ) {
1057 $title = $this->getTitle(); // Work arround E_STRICT
1058 $this->addWikiTextTitle( $text, $title, $linestart );
1062 * Add wikitext with a custom Title object
1064 * @param $text String: wikitext
1065 * @param $title Title object
1066 * @param $linestart Boolean: is this the start of a line?
1068 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1069 $this->addWikiTextTitle( $text, $title, $linestart );
1073 * Add wikitext with a custom Title object and
1075 * @param $text String: wikitext
1076 * @param $title Title object
1077 * @param $linestart Boolean: is this the start of a line?
1079 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1080 $this->addWikiTextTitle( $text, $title, $linestart, true );
1084 * Add wikitext with tidy enabled
1086 * @param $text String: wikitext
1087 * @param $linestart Boolean: is this the start of a line?
1089 public function addWikiTextTidy( $text, $linestart = true ) {
1090 $title = $this->getTitle();
1091 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1095 * Add wikitext with a custom Title object
1097 * @param $text String: wikitext
1098 * @param $title Title object
1099 * @param $linestart Boolean: is this the start of a line?
1100 * @param $tidy Boolean: whether to use tidy
1102 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1105 wfProfileIn( __METHOD__
);
1107 wfIncrStats( 'pcache_not_possible' );
1109 $popts = $this->parserOptions();
1110 $oldTidy = $popts->setTidy( $tidy );
1112 $parserOutput = $wgParser->parse(
1113 $text, $title, $popts,
1114 $linestart, true, $this->mRevisionId
1117 $popts->setTidy( $oldTidy );
1119 $this->addParserOutput( $parserOutput );
1121 wfProfileOut( __METHOD__
);
1125 * Add wikitext to the buffer, assuming that this is the primary text for a page view
1126 * Saves the text into the parser cache if possible.
1128 * @param $text String: wikitext
1129 * @param $article Article object
1130 * @param $cache Boolean
1131 * @deprecated Use Article::outputWikitext
1133 public function addPrimaryWikiText( $text, $article, $cache = true ) {
1136 wfDeprecated( __METHOD__
);
1138 $popts = $this->parserOptions();
1139 $popts->setTidy( true );
1140 $parserOutput = $wgParser->parse(
1141 $text, $article->mTitle
,
1142 $popts, true, true, $this->mRevisionId
1144 $popts->setTidy( false );
1145 if ( $cache && $article && $parserOutput->isCacheable() ) {
1146 $parserCache = ParserCache
::singleton();
1147 $parserCache->save( $parserOutput, $article, $popts );
1150 $this->addParserOutput( $parserOutput );
1154 * @deprecated use addWikiTextTidy()
1156 public function addSecondaryWikiText( $text, $linestart = true ) {
1157 wfDeprecated( __METHOD__
);
1158 $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
1162 * Add a ParserOutput object, but without Html
1164 * @param $parserOutput ParserOutput object
1166 public function addParserOutputNoText( &$parserOutput ) {
1167 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1168 $this->addCategoryLinks( $parserOutput->getCategories() );
1169 $this->mNewSectionLink
= $parserOutput->getNewSection();
1170 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1172 $this->mParseWarnings
= $parserOutput->getWarnings();
1173 if ( !$parserOutput->isCacheable() ) {
1174 $this->enableClientCache( false );
1176 $this->mNoGallery
= $parserOutput->getNoGallery();
1177 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1178 $this->addModules( $parserOutput->getModules() );
1180 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1181 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1182 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1184 $this->mTemplateIds
[$ns] = $dbks;
1188 // Hooks registered in the object
1189 global $wgParserOutputHooks;
1190 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1191 list( $hookName, $data ) = $hookInfo;
1192 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1193 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1197 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1201 * Add a ParserOutput object
1203 * @param $parserOutput ParserOutput
1205 function addParserOutput( &$parserOutput ) {
1206 $this->addParserOutputNoText( $parserOutput );
1207 $text = $parserOutput->getText();
1208 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1209 $this->addHTML( $text );
1214 * Add the output of a QuickTemplate to the output buffer
1216 * @param $template QuickTemplate
1218 public function addTemplate( &$template ) {
1220 $template->execute();
1221 $this->addHTML( ob_get_contents() );
1226 * Parse wikitext and return the HTML.
1228 * @param $text String
1229 * @param $linestart Boolean: is this the start of a line?
1230 * @param $interface Boolean: use interface language ($wgLang instead of
1231 * $wgContLang) while parsing language sensitive magic
1232 * words like GRAMMAR and PLURAL
1233 * @return String: HTML
1235 public function parse( $text, $linestart = true, $interface = false ) {
1237 if( is_null( $this->getTitle() ) ) {
1238 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1240 $popts = $this->parserOptions();
1242 $popts->setInterfaceMessage( true );
1244 $parserOutput = $wgParser->parse(
1245 $text, $this->getTitle(), $popts,
1246 $linestart, true, $this->mRevisionId
1249 $popts->setInterfaceMessage( false );
1251 return $parserOutput->getText();
1255 * Parse wikitext, strip paragraphs, and return the HTML.
1257 * @param $text String
1258 * @param $linestart Boolean: is this the start of a line?
1259 * @param $interface Boolean: use interface language ($wgLang instead of
1260 * $wgContLang) while parsing language sensitive magic
1261 * words like GRAMMAR and PLURAL
1262 * @return String: HTML
1264 public function parseInline( $text, $linestart = true, $interface = false ) {
1265 $parsed = $this->parse( $text, $linestart, $interface );
1268 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1278 * @param $article Article
1279 * @return Boolean: true if successful, else false.
1281 public function tryParserCache( &$article ) {
1282 wfDeprecated( __METHOD__
);
1283 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
1285 if ( $parserOutput !== false ) {
1286 $this->addParserOutput( $parserOutput );
1294 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1296 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1298 public function setSquidMaxage( $maxage ) {
1299 $this->mSquidMaxage
= $maxage;
1303 * Use enableClientCache(false) to force it to send nocache headers
1307 public function enableClientCache( $state ) {
1308 return wfSetVar( $this->mEnableClientCache
, $state );
1312 * Get the list of cookies that will influence on the cache
1316 function getCacheVaryCookies() {
1317 global $wgCookiePrefix, $wgCacheVaryCookies;
1319 if ( $cookies === null ) {
1320 $cookies = array_merge(
1322 "{$wgCookiePrefix}Token",
1323 "{$wgCookiePrefix}LoggedOut",
1328 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1334 * Return whether this page is not cacheable because "useskin" or "uselang"
1335 * URL parameters were passed.
1339 function uncacheableBecauseRequestVars() {
1341 return $wgRequest->getText( 'useskin', false ) === false
1342 && $wgRequest->getText( 'uselang', false ) === false;
1346 * Check if the request has a cache-varying cookie header
1347 * If it does, it's very important that we don't allow public caching
1351 function haveCacheVaryCookies() {
1353 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1354 if ( $cookieHeader === false ) {
1357 $cvCookies = $this->getCacheVaryCookies();
1358 foreach ( $cvCookies as $cookieName ) {
1359 # Check for a simple string match, like the way squid does it
1360 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1361 wfDebug( __METHOD__
. ": found $cookieName\n" );
1365 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1370 * Add an HTTP header that will influence on the cache
1372 * @param $header String: header name
1373 * @param $option either an Array or null
1375 public function addVaryHeader( $header, $option = null ) {
1376 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1377 $this->mVaryHeader
[$header] = $option;
1378 } elseif( is_array( $option ) ) {
1379 if( is_array( $this->mVaryHeader
[$header] ) ) {
1380 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1382 $this->mVaryHeader
[$header] = $option;
1385 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1389 * Get a complete X-Vary-Options header
1393 public function getXVO() {
1394 $cvCookies = $this->getCacheVaryCookies();
1396 $cookiesOption = array();
1397 foreach ( $cvCookies as $cookieName ) {
1398 $cookiesOption[] = 'string-contains=' . $cookieName;
1400 $this->addVaryHeader( 'Cookie', $cookiesOption );
1403 foreach( $this->mVaryHeader
as $header => $option ) {
1404 $newheader = $header;
1405 if( is_array( $option ) ) {
1406 $newheader .= ';' . implode( ';', $option );
1408 $headers[] = $newheader;
1410 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1416 * bug 21672: Add Accept-Language to Vary and XVO headers
1417 * if there's no 'variant' parameter existed in GET.
1420 * /w/index.php?title=Main_page should always be served; but
1421 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1423 function addAcceptLanguage() {
1424 global $wgRequest, $wgContLang;
1425 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1426 $variants = $wgContLang->getVariants();
1427 $aloption = array();
1428 foreach ( $variants as $variant ) {
1429 if( $variant === $wgContLang->getCode() ) {
1432 $aloption[] = "string-contains=$variant";
1435 $this->addVaryHeader( 'Accept-Language', $aloption );
1440 * Send cache control HTTP headers
1442 public function sendCacheControl() {
1443 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1445 $response = $wgRequest->response();
1446 if ( $wgUseETag && $this->mETag
) {
1447 $response->header( "ETag: $this->mETag" );
1450 $this->addAcceptLanguage();
1452 # don't serve compressed data to clients who can't handle it
1453 # maintain different caches for logged-in users and non-logged in ones
1454 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1457 # Add an X-Vary-Options header for Squid with Wikimedia patches
1458 $response->header( $this->getXVO() );
1461 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1463 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1464 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1468 # We'll purge the proxy cache explicitly, but require end user agents
1469 # to revalidate against the proxy on each visit.
1470 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1471 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1472 # start with a shorter timeout for initial testing
1473 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1474 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1475 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1477 # We'll purge the proxy cache for anons explicitly, but require end user agents
1478 # to revalidate against the proxy on each visit.
1479 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1480 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1481 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1482 # start with a shorter timeout for initial testing
1483 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1484 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1487 # We do want clients to cache if they can, but they *must* check for updates
1488 # on revisiting the page.
1489 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1490 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1491 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1493 if($this->mLastModified
) {
1494 $response->header( "Last-Modified: {$this->mLastModified}" );
1497 wfDebug( __METHOD__
. ": no caching **\n", false );
1499 # In general, the absence of a last modified header should be enough to prevent
1500 # the client from using its cache. We send a few other things just to make sure.
1501 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1502 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1503 $response->header( 'Pragma: no-cache' );
1508 * Get the message associed with the HTTP response code $code
1510 * @param $code Integer: status code
1511 * @return String or null: message or null if $code is not in the list of
1514 public static function getStatusMessage( $code ) {
1515 static $statusMessage = array(
1517 101 => 'Switching Protocols',
1518 102 => 'Processing',
1522 203 => 'Non-Authoritative Information',
1523 204 => 'No Content',
1524 205 => 'Reset Content',
1525 206 => 'Partial Content',
1526 207 => 'Multi-Status',
1527 300 => 'Multiple Choices',
1528 301 => 'Moved Permanently',
1531 304 => 'Not Modified',
1533 307 => 'Temporary Redirect',
1534 400 => 'Bad Request',
1535 401 => 'Unauthorized',
1536 402 => 'Payment Required',
1539 405 => 'Method Not Allowed',
1540 406 => 'Not Acceptable',
1541 407 => 'Proxy Authentication Required',
1542 408 => 'Request Timeout',
1545 411 => 'Length Required',
1546 412 => 'Precondition Failed',
1547 413 => 'Request Entity Too Large',
1548 414 => 'Request-URI Too Large',
1549 415 => 'Unsupported Media Type',
1550 416 => 'Request Range Not Satisfiable',
1551 417 => 'Expectation Failed',
1552 422 => 'Unprocessable Entity',
1554 424 => 'Failed Dependency',
1555 500 => 'Internal Server Error',
1556 501 => 'Not Implemented',
1557 502 => 'Bad Gateway',
1558 503 => 'Service Unavailable',
1559 504 => 'Gateway Timeout',
1560 505 => 'HTTP Version Not Supported',
1561 507 => 'Insufficient Storage'
1563 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1567 * Finally, all the text has been munged and accumulated into
1568 * the object, let's actually output it:
1570 public function output() {
1571 global $wgUser, $wgOutputEncoding, $wgRequest;
1572 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1573 global $wgUseAjax, $wgAjaxWatch;
1574 global $wgEnableMWSuggest, $wgUniversalEditButton;
1577 if( $this->mDoNothing
) {
1580 wfProfileIn( __METHOD__
);
1581 if ( $this->mRedirect
!= '' ) {
1582 # Standards require redirect URLs to be absolute
1583 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1584 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1585 if( !$wgDebugRedirects ) {
1586 $message = self
::getStatusMessage( $this->mRedirectCode
);
1587 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1589 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1591 $this->sendCacheControl();
1593 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1594 if( $wgDebugRedirects ) {
1595 $url = htmlspecialchars( $this->mRedirect
);
1596 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1597 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1598 print "</body>\n</html>\n";
1600 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1602 wfProfileOut( __METHOD__
);
1604 } elseif ( $this->mStatusCode
) {
1605 $message = self
::getStatusMessage( $this->mStatusCode
);
1607 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1611 $sk = $wgUser->getSkin();
1613 // Add base resources
1614 $this->addModules( array( 'mediawiki.legacy.wikibits' ) );
1616 // Add various resources if required
1618 $this->addModules( 'mediawiki.legacy.ajax' );
1620 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1622 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1623 $this->addModules( 'mediawiki.legacy.ajaxwatch' );
1626 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1627 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1631 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1632 $this->addModules( 'mediawiki.legacy.rightclickedit' );
1635 if( $wgUniversalEditButton ) {
1636 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1637 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1638 // Original UniversalEditButton
1639 $msg = wfMsg( 'edit' );
1640 $this->addLink( array(
1641 'rel' => 'alternate',
1642 'type' => 'application/x-wiki',
1644 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1646 // Alternate edit link
1647 $this->addLink( array(
1650 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1656 # Buffer output; final headers may depend on later processing
1659 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1660 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1662 if ( $this->mArticleBodyOnly
) {
1663 $this->out( $this->mBodytext
);
1665 // Hook that allows last minute changes to the output page, e.g.
1666 // adding of CSS or Javascript by extensions.
1667 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1669 wfProfileIn( 'Output-skin' );
1670 $sk->outputPage( $this );
1671 wfProfileOut( 'Output-skin' );
1674 $this->sendCacheControl();
1676 wfProfileOut( __METHOD__
);
1680 * Actually output something with print(). Performs an iconv to the
1681 * output encoding, if needed.
1683 * @param $ins String: the string to output
1685 public function out( $ins ) {
1686 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1687 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1690 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1691 if ( false === $outs ) {
1701 public static function setEncodings() {
1702 global $wgInputEncoding, $wgOutputEncoding;
1704 $wgInputEncoding = strtolower( $wgInputEncoding );
1706 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1707 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1710 $wgOutputEncoding = $wgInputEncoding;
1714 * @deprecated use wfReportTime() instead.
1718 public function reportTime() {
1719 wfDeprecated( __METHOD__
);
1720 $time = wfReportTime();
1725 * Produce a "user is blocked" page.
1727 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1730 function blockedPage( $return = true ) {
1731 global $wgUser, $wgContLang, $wgLang;
1733 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1734 $this->setRobotPolicy( 'noindex,nofollow' );
1735 $this->setArticleRelated( false );
1737 $name = User
::whoIs( $wgUser->blockedBy() );
1738 $reason = $wgUser->blockedFor();
1739 if( $reason == '' ) {
1740 $reason = wfMsg( 'blockednoreason' );
1742 $blockTimestamp = $wgLang->timeanddate(
1743 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1747 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1749 $blockid = $wgUser->mBlock
->mId
;
1751 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1752 if ( $blockExpiry == 'infinity' ) {
1753 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1754 // Search for localization in 'ipboptions'
1755 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1756 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1757 if ( strpos( $option, ':' ) === false ) {
1760 list( $show, $value ) = explode( ':', $option );
1761 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1762 $blockExpiry = $show;
1767 $blockExpiry = $wgLang->timeanddate(
1768 wfTimestamp( TS_MW
, $blockExpiry ),
1773 if ( $wgUser->mBlock
->mAuto
) {
1774 $msg = 'autoblockedtext';
1776 $msg = 'blockedtext';
1779 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1780 * This could be a username, an IP range, or a single IP. */
1781 $intended = $wgUser->mBlock
->mAddress
;
1784 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1785 $intended, $blockTimestamp
1788 # Don't auto-return to special pages
1790 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1791 $this->returnToMain( null, $return );
1796 * Output a standard error page
1798 * @param $title String: message key for page title
1799 * @param $msg String: message key for page text
1800 * @param $params Array: message parameters
1802 public function showErrorPage( $title, $msg, $params = array() ) {
1803 if ( $this->getTitle() ) {
1804 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1806 $this->setPageTitle( wfMsg( $title ) );
1807 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1808 $this->setRobotPolicy( 'noindex,nofollow' );
1809 $this->setArticleRelated( false );
1810 $this->enableClientCache( false );
1811 $this->mRedirect
= '';
1812 $this->mBodytext
= '';
1814 array_unshift( $params, 'parse' );
1815 array_unshift( $params, $msg );
1816 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1818 $this->returnToMain();
1822 * Output a standard permission error page
1824 * @param $errors Array: error message keys
1825 * @param $action String: action that was denied or null if unknown
1827 public function showPermissionsErrorPage( $errors, $action = null ) {
1828 $this->mDebugtext
.= 'Original title: ' .
1829 $this->getTitle()->getPrefixedText() . "\n";
1830 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1831 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1832 $this->setRobotPolicy( 'noindex,nofollow' );
1833 $this->setArticleRelated( false );
1834 $this->enableClientCache( false );
1835 $this->mRedirect
= '';
1836 $this->mBodytext
= '';
1837 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1841 * Display an error page indicating that a given version of MediaWiki is
1842 * required to use it
1844 * @param $version Mixed: the version of MediaWiki needed to use the page
1846 public function versionRequired( $version ) {
1847 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1848 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1849 $this->setRobotPolicy( 'noindex,nofollow' );
1850 $this->setArticleRelated( false );
1851 $this->mBodytext
= '';
1853 $this->addWikiMsg( 'versionrequiredtext', $version );
1854 $this->returnToMain();
1858 * Display an error page noting that a given permission bit is required.
1860 * @param $permission String: key required
1862 public function permissionRequired( $permission ) {
1865 $this->setPageTitle( wfMsg( 'badaccess' ) );
1866 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1867 $this->setRobotPolicy( 'noindex,nofollow' );
1868 $this->setArticleRelated( false );
1869 $this->mBodytext
= '';
1871 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1872 User
::getGroupsWithPermission( $permission ) );
1876 $wgLang->commaList( $groups ),
1880 $this->addWikiMsg( 'badaccess-group0' );
1882 $this->returnToMain();
1886 * Produce the stock "please login to use the wiki" page
1888 public function loginToUse() {
1891 if( $wgUser->isLoggedIn() ) {
1892 $this->permissionRequired( 'read' );
1896 $skin = $wgUser->getSkin();
1898 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1899 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1900 $this->setRobotPolicy( 'noindex,nofollow' );
1901 $this->setArticleFlag( false );
1903 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1904 $loginLink = $skin->link(
1906 wfMsgHtml( 'loginreqlink' ),
1908 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1909 array( 'known', 'noclasses' )
1911 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1912 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1914 # Don't return to the main page if the user can't read it
1915 # otherwise we'll end up in a pointless loop
1916 $mainPage = Title
::newMainPage();
1917 if( $mainPage->userCanRead() ) {
1918 $this->returnToMain( null, $mainPage );
1923 * Format a list of error messages
1925 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1926 * @param $action String: action that was denied or null if unknown
1927 * @return String: the wikitext error-messages, formatted into a list.
1929 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1930 if ( $action == null ) {
1931 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1933 $action_desc = wfMsgNoTrans( "action-$action" );
1934 $text = wfMsgNoTrans(
1935 'permissionserrorstext-withaction',
1941 if ( count( $errors ) > 1 ) {
1942 $text .= '<ul class="permissions-errors">' . "\n";
1944 foreach( $errors as $error ) {
1946 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1951 $text .= "<div class=\"permissions-errors\">\n" .
1952 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
1960 * Display a page stating that the Wiki is in read-only mode,
1961 * and optionally show the source of the page that the user
1962 * was trying to edit. Should only be called (for this
1963 * purpose) after wfReadOnly() has returned true.
1965 * For historical reasons, this function is _also_ used to
1966 * show the error message when a user tries to edit a page
1967 * they are not allowed to edit. (Unless it's because they're
1968 * blocked, then we show blockedPage() instead.) In this
1969 * case, the second parameter should be set to true and a list
1970 * of reasons supplied as the third parameter.
1972 * @todo Needs to be split into multiple functions.
1974 * @param $source String: source code to show (or null).
1975 * @param $protected Boolean: is this a permissions error?
1976 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1977 * @param $action String: action that was denied or null if unknown
1979 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1981 $skin = $wgUser->getSkin();
1983 $this->setRobotPolicy( 'noindex,nofollow' );
1984 $this->setArticleRelated( false );
1986 // If no reason is given, just supply a default "I can't let you do
1987 // that, Dave" message. Should only occur if called by legacy code.
1988 if ( $protected && empty( $reasons ) ) {
1989 $reasons[] = array( 'badaccess-group0' );
1992 if ( !empty( $reasons ) ) {
1993 // Permissions error
1995 $this->setPageTitle( wfMsg( 'viewsource' ) );
1997 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2000 $this->setPageTitle( wfMsg( 'badaccess' ) );
2002 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2004 // Wiki is read only
2005 $this->setPageTitle( wfMsg( 'readonly' ) );
2006 $reason = wfReadOnlyReason();
2007 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2010 // Show source, if supplied
2011 if( is_string( $source ) ) {
2012 $this->addWikiMsg( 'viewsourcetext' );
2015 'id' => 'wpTextbox1',
2016 'name' => 'wpTextbox1',
2017 'cols' => $wgUser->getOption( 'cols' ),
2018 'rows' => $wgUser->getOption( 'rows' ),
2019 'readonly' => 'readonly'
2021 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2023 // Show templates used by this article
2024 $skin = $wgUser->getSkin();
2025 $article = new Article( $this->getTitle() );
2026 $this->addHTML( "<div class='templatesUsed'>
2027 {$skin->formatTemplates( $article->getUsedTemplates() )}
2032 # If the title doesn't exist, it's fairly pointless to print a return
2033 # link to it. After all, you just tried editing it and couldn't, so
2034 # what's there to do there?
2035 if( $this->getTitle()->exists() ) {
2036 $this->returnToMain( null, $this->getTitle() );
2041 * Adds JS-based password security checker
2042 * @param $passwordId String ID of input box containing password
2043 * @param $retypeId String ID of input box containing retyped password
2046 public function addPasswordSecurity( $passwordId, $retypeId ) {
2047 $this->includeJQuery();
2049 'password' => '#' . $passwordId,
2050 'retype' => '#' . $retypeId,
2051 'messages' => array(),
2053 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2054 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2056 $data['messages'][$message] = wfMsg( $message );
2058 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2059 $this->addModules( 'mediawiki.legacy.password' );
2063 public function errorpage( $title, $msg ) {
2064 wfDeprecated( __METHOD__
);
2065 throw new ErrorPageError( $title, $msg );
2069 public function databaseError( $fname, $sql, $error, $errno ) {
2070 throw new MWException( "OutputPage::databaseError is obsolete\n" );
2074 public function fatalError( $message ) {
2075 wfDeprecated( __METHOD__
);
2076 throw new FatalError( $message );
2080 public function unexpectedValueError( $name, $val ) {
2081 wfDeprecated( __METHOD__
);
2082 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
2086 public function fileCopyError( $old, $new ) {
2087 wfDeprecated( __METHOD__
);
2088 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
2092 public function fileRenameError( $old, $new ) {
2093 wfDeprecated( __METHOD__
);
2094 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
2098 public function fileDeleteError( $name ) {
2099 wfDeprecated( __METHOD__
);
2100 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
2104 public function fileNotFoundError( $name ) {
2105 wfDeprecated( __METHOD__
);
2106 throw new FatalError( wfMsg( 'filenotfound', $name ) );
2109 public function showFatalError( $message ) {
2110 $this->setPageTitle( wfMsg( 'internalerror' ) );
2111 $this->setRobotPolicy( 'noindex,nofollow' );
2112 $this->setArticleRelated( false );
2113 $this->enableClientCache( false );
2114 $this->mRedirect
= '';
2115 $this->mBodytext
= $message;
2118 public function showUnexpectedValueError( $name, $val ) {
2119 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2122 public function showFileCopyError( $old, $new ) {
2123 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2126 public function showFileRenameError( $old, $new ) {
2127 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2130 public function showFileDeleteError( $name ) {
2131 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2134 public function showFileNotFoundError( $name ) {
2135 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2139 * Add a "return to" link pointing to a specified title
2141 * @param $title Title to link
2142 * @param $query String: query string
2143 * @param $text String text of the link (input is not escaped)
2145 public function addReturnTo( $title, $query = array(), $text = null ) {
2147 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2150 $wgUser->getSkin()->link( $title, $text, array(), $query )
2152 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2156 * Add a "return to" link pointing to a specified title,
2157 * or the title indicated in the request, or else the main page
2159 * @param $unused No longer used
2160 * @param $returnto Title or String to return to
2161 * @param $returntoquery String: query string for the return to link
2163 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2166 if ( $returnto == null ) {
2167 $returnto = $wgRequest->getText( 'returnto' );
2170 if ( $returntoquery == null ) {
2171 $returntoquery = $wgRequest->getText( 'returntoquery' );
2174 if ( $returnto === '' ) {
2175 $returnto = Title
::newMainPage();
2178 if ( is_object( $returnto ) ) {
2179 $titleObj = $returnto;
2181 $titleObj = Title
::newFromText( $returnto );
2183 if ( !is_object( $titleObj ) ) {
2184 $titleObj = Title
::newMainPage();
2187 $this->addReturnTo( $titleObj, $returntoquery );
2191 * @param $sk Skin The given Skin
2192 * @param $includeStyle Boolean: unused
2193 * @return String: The doctype, opening <html>, and head element.
2195 public function headElement( Skin
$sk, $includeStyle = true ) {
2196 global $wgOutputEncoding, $wgMimeType;
2197 global $wgUseTrackbacks, $wgHtml5;
2198 global $wgUser, $wgRequest, $wgLang;
2200 if ( $sk->commonPrintStylesheet() ) {
2201 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2203 $sk->setupUserCss( $this );
2205 $ret = Html
::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2207 if ( $this->getHTMLTitle() == '' ) {
2208 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2211 $openHead = Html
::openElement( 'head' );
2213 # Don't bother with the newline if $head == ''
2214 $ret .= "$openHead\n";
2218 # More succinct than <meta http-equiv=Content-Type>, has the
2220 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2222 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2225 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2227 $ret .= implode( "\n", array(
2228 $this->getHeadLinks( $sk ),
2229 $this->buildCssLinks(),
2230 $this->getHeadItems(),
2232 if ( $sk->usercss
) {
2233 $ret .= Html
::inlineStyle( $sk->usercss
);
2236 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2237 $ret .= $this->getTitle()->trackbackRDF();
2240 $closeHead = Html
::closeElement( 'head' );
2242 $ret .= "$closeHead\n";
2245 $bodyAttrs = array();
2247 # Crazy edit-on-double-click stuff
2248 $action = $wgRequest->getVal( 'action', 'view' );
2251 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2252 !in_array( $action, array( 'edit', 'submit' ) ) &&
2253 $wgUser->getOption( 'editondblclick' )
2256 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2260 $dir = wfUILang()->getDir();
2261 $bodyAttrs['class'] = "mediawiki $dir";
2263 if ( $wgLang->capitalizeAllNouns() ) {
2264 # A <body> class is probably not the best way to do this . . .
2265 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2267 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2268 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
2269 $bodyAttrs['class'] .= ' ns-special';
2270 } elseif ( $this->getTitle()->isTalkPage() ) {
2271 $bodyAttrs['class'] .= ' ns-talk';
2273 $bodyAttrs['class'] .= ' ns-subject';
2275 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2276 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
2278 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2284 static function makeResourceLoaderLink( $skin, $modules, $only, $useESI = false ) {
2285 global $wgUser, $wgLang, $wgRequest, $wgLoadScript, $wgResourceLoaderDebug, $wgResourceLoaderUseESI;
2286 // TODO: Should this be a static function of ResourceLoader instead?
2287 // TODO: Divide off modules starting with "user", and add the user parameter to them
2289 'lang' => $wgLang->getCode(),
2290 'debug' => $wgRequest->getFuzzyBool( 'debug', $wgResourceLoaderDebug ) ?
'true' : 'false',
2291 'skin' => $wgUser->getSkin()->getSkinName(),
2294 // Remove duplicate module requests
2295 $modules = array_unique( (array) $modules );
2296 // Sort module names so requests are more uniform
2298 // Create keyed-by-group list of module objects from modules list
2300 foreach ( (array) $modules as $name ) {
2301 $module = ResourceLoader
::getModule( $name );
2302 $group = $module->getGroup();
2303 if ( !isset( $groups[$group] ) ) {
2304 $groups[$group] = array();
2306 $groups[$group][$name] = $module;
2309 foreach ( $groups as $group => $modules ) {
2310 $query['modules'] = implode( '|', array_keys( $modules ) );
2311 // Special handling for user group
2312 if ( $group === 'user' && $wgUser->isLoggedIn() ) {
2313 $query['user'] = $wgUser->getName();
2315 // Special handling for user and site groups; because users might change their stuff on-wiki like site or
2316 // user pages, or user preferences; we need to find the highest timestamp of these user-changable modules so
2317 // we can ensure cache misses on change
2318 if ( $group === 'user' ||
$group === 'site' ) {
2319 // Create a fake request based on the one we are about to make so modules return correct times
2320 $request = new ResourceLoaderContext( new FauxRequest( $query ) );
2321 // Get the maximum timestamp
2323 foreach ( $modules as $module ) {
2324 $timestamp = max( $timestamp, $module->getModifiedTime( $request ) );
2326 // Add a version parameter so cache will break when things change
2327 $query['version'] = wfTimestamp( TS_ISO_8601
, round( $timestamp, -2 ) );
2329 // Make queries uniform in order
2332 $url = wfAppendQuery( $wgLoadScript, $query );
2333 if ( $useESI && $wgResourceLoaderUseESI ) {
2334 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2335 if ( $only == 'styles' ) {
2336 $links .= Html
::inlineStyle( $esi );
2338 $links .= Html
::inlineScript( $esi );
2341 // Automatically select style/script elements
2342 if ( $only === 'styles' ) {
2343 $links .= Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2345 $links .= Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2353 * Gets the global variables and mScripts; also adds userjs to the end if
2354 * enabled. Despite the name, these scripts are no longer put in the
2355 * <head> but at the bottom of the <body>
2357 * @param $sk Skin object to use
2358 * @return String: HTML fragment
2360 function getHeadScripts( Skin
$sk ) {
2361 global $wgUser, $wgRequest, $wgUseSiteJs, $wgResourceLoaderDebug;
2363 // Startup - this will immediately load jquery and mediawiki modules
2364 $scripts = self
::makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2366 // Configuration -- This could be merged together with the load and go, but makeGlobalVariablesScript returns a
2367 // whole script tag -- grumble grumble...
2368 $scripts .= Skin
::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2370 // Script and Messages "only"
2371 if ( $wgRequest->getFuzzyBool( 'debug', $wgResourceLoaderDebug ) ) {
2373 foreach ( $this->getModuleScripts() as $name ) {
2374 $scripts .= self
::makeResourceLoaderLink( $sk, $name, 'scripts' );
2377 foreach ( $this->getModuleMessages() as $name ) {
2378 $scripts .= self
::makeResourceLoaderLink( $sk, $name, 'messages' );
2382 if ( count( $this->getModuleScripts() ) ) {
2383 $scripts .= self
::makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2386 if ( count( $this->getModuleMessages() ) ) {
2387 $scripts .= self
::makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2391 // Modules - let the client calculate dependencies and batch requests as it likes
2392 if ( $this->getModules() ) {
2393 $modules = FormatJson
::encode( $this->getModules() );
2394 $scripts .= Html
::inlineScript(
2395 "if ( window.mediaWiki ) { mediaWiki.loader.load( {$modules} ); mediaWiki.loader.go(); }"
2399 // Add user JS if enabled - trying to load user.options as a bundle if possible
2400 $userOptionsAdded = false;
2401 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2402 $action = $wgRequest->getVal( 'action', 'view' );
2403 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2404 # XXX: additional security check/prompt?
2405 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2407 $scripts .= self
::makeResourceLoaderLink( $sk, array( 'user', 'user.options' ), 'scripts' );
2408 $userOptionsAdded = true;
2411 if ( !$userOptionsAdded ) {
2412 $scripts .= self
::makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2414 $scripts .= "\n" . $this->mScripts
;
2416 // Add site JS if enabled
2417 if ( $wgUseSiteJs ) {
2418 $scripts .= self
::makeResourceLoaderLink( $sk, 'site', 'scripts' );
2425 * Add default \<meta\> tags
2427 protected function addDefaultMeta() {
2428 global $wgVersion, $wgHtml5;
2430 static $called = false;
2432 # Don't run this twice
2438 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2440 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2442 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2443 if( $p !== 'index,follow' ) {
2444 // http://www.robotstxt.org/wc/meta-user.html
2445 // Only show if it's different from the default robots policy
2446 $this->addMeta( 'robots', $p );
2449 if ( count( $this->mKeywords
) > 0 ) {
2451 "/<.*?" . ">/" => '',
2457 array_keys( $strip ),
2458 array_values( $strip ),
2459 implode( ',', $this->mKeywords
)
2466 * @return string HTML tag links to be put in the header.
2468 public function getHeadLinks( $sk ) {
2469 global $wgFeed, $wgRequest, $wgResourceLoaderDebug;
2471 // Ideally this should happen earlier, somewhere. :P
2472 $this->addDefaultMeta();
2476 foreach ( $this->mMetatags
as $tag ) {
2477 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2479 $tag[0] = substr( $tag[0], 5 );
2483 $tags[] = Html
::element( 'meta',
2486 'content' => $tag[1]
2490 foreach ( $this->mLinktags
as $tag ) {
2491 $tags[] = Html
::element( 'link', $tag );
2495 foreach( $this->getSyndicationLinks() as $format => $link ) {
2496 # Use the page name for the title (accessed through $wgTitle since
2497 # there's no other way). In principle, this could lead to issues
2498 # with having the same name for different feeds corresponding to
2499 # the same page, but we can't avoid that at this low a level.
2501 $tags[] = $this->feedLink(
2504 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2505 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2509 # Recent changes feed should appear on every page (except recentchanges,
2510 # that would be redundant). Put it after the per-page feed to avoid
2511 # changing existing behavior. It's still available, probably via a
2512 # menu in your browser. Some sites might have a different feed they'd
2513 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2514 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2515 # If so, use it instead.
2517 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2518 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2520 if ( $wgOverrideSiteFeed ) {
2521 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2522 $tags[] = $this->feedLink(
2524 htmlspecialchars( $feedUrl ),
2525 wfMsg( "site-{$type}-feed", $wgSitename )
2528 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2529 foreach ( $wgAdvertisedFeedTypes as $format ) {
2530 $tags[] = $this->feedLink(
2532 $rctitle->getLocalURL( "feed={$format}" ),
2533 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2539 // Support individual script requests in debug mode
2540 if ( $wgRequest->getFuzzyBool( 'debug', $wgResourceLoaderDebug ) ) {
2541 foreach ( $this->getModuleStyles() as $name ) {
2542 $tags[] = self
::makeResourceLoaderLink( $sk, $name, 'styles' );
2545 if ( count( $this->getModuleStyles() ) ) {
2546 $tags[] = self
::makeResourceLoaderLink( $sk, $this->getModuleStyles(), 'styles' );
2550 return implode( "\n", $tags );
2554 * Generate a <link rel/> for a feed.
2556 * @param $type String: feed type
2557 * @param $url String: URL to the feed
2558 * @param $text String: value of the "title" attribute
2559 * @return String: HTML fragment
2561 private function feedLink( $type, $url, $text ) {
2562 return Html
::element( 'link', array(
2563 'rel' => 'alternate',
2564 'type' => "application/$type+xml",
2571 * Add a local or specified stylesheet, with the given media options.
2572 * Meant primarily for internal use...
2574 * @param $style String: URL to the file
2575 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2576 * @param $condition String: for IE conditional comments, specifying an IE version
2577 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2579 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2581 // Even though we expect the media type to be lowercase, but here we
2582 // force it to lowercase to be safe.
2584 $options['media'] = $media;
2587 $options['condition'] = $condition;
2590 $options['dir'] = $dir;
2592 $this->styles
[$style] = $options;
2596 * Adds inline CSS styles
2597 * @param $style_css Mixed: inline CSS
2599 public function addInlineStyle( $style_css ){
2600 $this->mScripts
.= Html
::inlineStyle( $style_css );
2604 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2605 * These will be applied to various media & IE conditionals.
2607 public function buildCssLinks() {
2608 return implode( "\n", $this->buildCssLinksArray() );
2611 public function buildCssLinksArray() {
2613 foreach( $this->styles
as $file => $options ) {
2614 $link = $this->styleLink( $file, $options );
2616 $links[$file] = $link;
2623 * Generate \<link\> tags for stylesheets
2625 * @param $style String: URL to the file
2626 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2628 * @return String: HTML fragment
2630 protected function styleLink( $style, $options ) {
2631 if( isset( $options['dir'] ) ) {
2632 $siteDir = wfUILang()->getDir();
2633 if( $siteDir != $options['dir'] ) {
2638 if( isset( $options['media'] ) ) {
2639 $media = $this->transformCssMedia( $options['media'] );
2640 if( is_null( $media ) ) {
2647 if( substr( $style, 0, 1 ) == '/' ||
2648 substr( $style, 0, 5 ) == 'http:' ||
2649 substr( $style, 0, 6 ) == 'https:' ) {
2652 global $wgStylePath, $wgStyleVersion;
2653 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2656 $link = Html
::linkedStyle( $url, $media );
2658 if( isset( $options['condition'] ) ) {
2659 $condition = htmlspecialchars( $options['condition'] );
2660 $link = "<!--[if $condition]>$link<![endif]-->";
2666 * Transform "media" attribute based on request parameters
2668 * @param $media String: current value of the "media" attribute
2669 * @return String: modified value of the "media" attribute
2671 function transformCssMedia( $media ) {
2672 global $wgRequest, $wgHandheldForIPhone;
2674 // Switch in on-screen display for media testing
2676 'printable' => 'print',
2677 'handheld' => 'handheld',
2679 foreach( $switches as $switch => $targetMedia ) {
2680 if( $wgRequest->getBool( $switch ) ) {
2681 if( $media == $targetMedia ) {
2683 } elseif( $media == 'screen' ) {
2689 // Expand longer media queries as iPhone doesn't grok 'handheld'
2690 if( $wgHandheldForIPhone ) {
2691 $mediaAliases = array(
2692 'screen' => 'screen and (min-device-width: 481px)',
2693 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2696 if( isset( $mediaAliases[$media] ) ) {
2697 $media = $mediaAliases[$media];
2705 * Turn off regular page output and return an error reponse
2706 * for when rate limiting has triggered.
2708 public function rateLimited() {
2709 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2710 $this->setRobotPolicy( 'noindex,follow' );
2711 $this->setArticleRelated( false );
2712 $this->enableClientCache( false );
2713 $this->mRedirect
= '';
2715 $this->setStatusCode( 503 );
2716 $this->addWikiMsg( 'actionthrottledtext' );
2718 $this->returnToMain( null, $this->getTitle() );
2722 * Show a warning about slave lag
2724 * If the lag is higher than $wgSlaveLagCritical seconds,
2725 * then the warning is a bit more obvious. If the lag is
2726 * lower than $wgSlaveLagWarning, then no warning is shown.
2728 * @param $lag Integer: slave lag
2730 public function showLagWarning( $lag ) {
2731 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2732 if( $lag >= $wgSlaveLagWarning ) {
2733 $message = $lag < $wgSlaveLagCritical
2736 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2737 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2742 * Add a wikitext-formatted message to the output.
2743 * This is equivalent to:
2745 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2747 public function addWikiMsg( /*...*/ ) {
2748 $args = func_get_args();
2749 $name = array_shift( $args );
2750 $this->addWikiMsgArray( $name, $args );
2754 * Add a wikitext-formatted message to the output.
2755 * Like addWikiMsg() except the parameters are taken as an array
2756 * instead of a variable argument list.
2758 * $options is passed through to wfMsgExt(), see that function for details.
2760 public function addWikiMsgArray( $name, $args, $options = array() ) {
2761 $options[] = 'parse';
2762 $text = wfMsgExt( $name, $options, $args );
2763 $this->addHTML( $text );
2767 * This function takes a number of message/argument specifications, wraps them in
2768 * some overall structure, and then parses the result and adds it to the output.
2770 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2771 * on. The subsequent arguments may either be strings, in which case they are the
2772 * message names, or arrays, in which case the first element is the message name,
2773 * and subsequent elements are the parameters to that message.
2775 * The special named parameter 'options' in a message specification array is passed
2776 * through to the $options parameter of wfMsgExt().
2778 * Don't use this for messages that are not in users interface language.
2782 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2786 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2788 * The newline after opening div is needed in some wikitext. See bug 19226.
2790 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2791 $msgSpecs = func_get_args();
2792 array_shift( $msgSpecs );
2793 $msgSpecs = array_values( $msgSpecs );
2795 foreach ( $msgSpecs as $n => $spec ) {
2797 if ( is_array( $spec ) ) {
2799 $name = array_shift( $args );
2800 if ( isset( $args['options'] ) ) {
2801 $options = $args['options'];
2802 unset( $args['options'] );
2808 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2810 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2814 * Include jQuery core. Use this to avoid loading it multiple times
2815 * before we get a usable script loader.
2817 * @param $modules Array: list of jQuery modules which should be loaded
2818 * @return Array: the list of modules which were not loaded.
2820 * @deprecated No longer needed as of 1.17
2822 public function includeJQuery( $modules = array() ) {