f87a6d90ce3bd8d638718868b1e2ff49ff4425f1
2 if ( ! defined( 'MEDIAWIKI' ) )
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
17 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
18 var $mInlineMsg = array();
20 var $mTemplateIds = array();
23 var $mSuppressQuickbar = false;
24 var $mDoNothing = false;
25 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
26 var $mIsArticleRelated = true;
27 protected $mParserOptions = null; // lazy initialised, use parserOptions()
29 var $mFeedLinks = array();
31 var $mEnableClientCache = true;
32 var $mArticleBodyOnly = false;
34 var $mNewSectionLink = false;
35 var $mHideNewSectionLink = false;
36 var $mNoGallery = false;
37 var $mPageTitleActionText = '';
38 var $mParseWarnings = array();
39 var $mSquidMaxage = 0;
40 var $mRevisionId = null;
41 protected $mTitle = null;
44 * An array of stylesheet filenames (relative from skins path), with options
45 * for CSS media, IE conditions, and RTL/LTR direction.
46 * For internal use; add settings in the skin via $this->addStyle()
48 var $styles = array();
51 * Whether to load jQuery core.
53 protected $mJQueryDone = false;
55 private $mIndexPolicy = 'index';
56 private $mFollowPolicy = 'follow';
57 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
63 * Initialise private variables
65 function __construct() {
66 global $wgAllowUserJs;
67 $this->mAllowUserJs
= $wgAllowUserJs;
71 * Redirect to $url rather than displaying the normal page
73 * @param $url String: URL
74 * @param $responsecode String: HTTP status code
76 public function redirect( $url, $responsecode = '302' ) {
77 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
78 $this->mRedirect
= str_replace( "\n", '', $url );
79 $this->mRedirectCode
= $responsecode;
83 * Get the URL to redirect to, or an empty string if not redirect URL set
87 public function getRedirect() {
88 return $this->mRedirect
;
92 * Set the HTTP status code to send with the output.
94 * @param $statusCode Integer
97 public function setStatusCode( $statusCode ) {
98 $this->mStatusCode
= $statusCode;
103 * Add a new <meta> tag
104 * To add an http-equiv meta tag, precede the name with "http:"
106 * @param $name tag name
107 * @param $val tag value
109 function addMeta( $name, $val ) {
110 array_push( $this->mMetatags
, array( $name, $val ) );
114 * Add a keyword or a list of keywords in the page header
116 * @param $text String or array of strings
118 function addKeyword( $text ) {
119 if( is_array( $text ) ) {
120 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
122 array_push( $this->mKeywords
, $text );
127 * Add a new \<link\> tag to the page header
129 * @param $linkarr Array: associative array of attributes.
131 function addLink( $linkarr ) {
132 array_push( $this->mLinktags
, $linkarr );
136 * Add a new \<link\> with "rel" attribute set to "meta"
138 * @param $linkarr Array: associative array mapping attribute names to their
139 * values, both keys and values will be escaped, and the
140 * "rel" attribute will be automatically added
142 function addMetadataLink( $linkarr ) {
143 # note: buggy CC software only reads first "meta" link
144 static $haveMeta = false;
145 $linkarr['rel'] = $haveMeta ?
'alternate meta' : 'meta';
146 $this->addLink( $linkarr );
152 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
154 * @param $script String: raw HTML
156 function addScript( $script ) {
157 $this->mScripts
.= $script . "\n";
161 * Register and add a stylesheet from an extension directory.
163 * @param $url String path to sheet. Provide either a full url (beginning
164 * with 'http', etc) or a relative path from the document root
165 * (beginning with '/'). Otherwise it behaves identically to
166 * addStyle() and draws from the /skins folder.
168 public function addExtensionStyle( $url ) {
169 array_push( $this->mExtStyles
, $url );
173 * Get all links added by extensions
177 function getExtStyle() {
178 return $this->mExtStyles
;
182 * Add a JavaScript file out of skins/common, or a given relative path.
184 * @param $file String: filename in skins/common or complete on-server path
187 public function addScriptFile( $file ) {
188 global $wgStylePath, $wgStyleVersion;
189 if( substr( $file, 0, 1 ) == '/' ) {
192 $path = "{$wgStylePath}/common/{$file}";
194 $this->addScript( Html
::linkedScript( "$path?$wgStyleVersion" ) );
198 * Add a self-contained script tag with the given contents
200 * @param $script String: JavaScript text, no <script> tags
202 public function addInlineScript( $script ) {
203 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
207 * Get all registered JS and CSS tags for the header.
211 function getScript() {
212 return $this->mScripts
. $this->getHeadItems();
216 * Get all header items in a string
220 function getHeadItems() {
222 foreach ( $this->mHeadItems
as $item ) {
229 * Add or replace an header item to the output
231 * @param $name String: item name
232 * @param $value String: raw HTML
234 public function addHeadItem( $name, $value ) {
235 $this->mHeadItems
[$name] = $value;
239 * Check if the header item $name is already set
241 * @param $name String: item name
244 public function hasHeadItem( $name ) {
245 return isset( $this->mHeadItems
[$name] );
249 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
251 * @param $tag String: value of "ETag" header
253 function setETag( $tag ) {
258 * Set whether the output should only contain the body of the article,
259 * without any skin, sidebar, etc.
260 * Used e.g. when calling with "action=raw".
262 * @param $only Boolean: whether to output only the body of the article
264 public function setArticleBodyOnly( $only ) {
265 $this->mArticleBodyOnly
= $only;
269 * Return whether the output will contain only the body of the article
273 public function getArticleBodyOnly() {
274 return $this->mArticleBodyOnly
;
279 * checkLastModified tells the client to use the client-cached page if
280 * possible. If sucessful, the OutputPage is disabled so that
281 * any future call to OutputPage->output() have no effect.
283 * Side effect: sets mLastModified for Last-Modified header
285 * @return Boolean: true iff cache-ok headers was sent.
287 public function checkLastModified( $timestamp ) {
288 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
290 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
291 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
294 if( !$wgCachePages ) {
295 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
298 if( $wgUser->getOption( 'nocache' ) ) {
299 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
303 $timestamp = wfTimestamp( TS_MW
, $timestamp );
304 $modifiedTimes = array(
305 'page' => $timestamp,
306 'user' => $wgUser->getTouched(),
307 'epoch' => $wgCacheEpoch
309 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
311 $maxModified = max( $modifiedTimes );
312 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
314 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
315 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
321 foreach ( $modifiedTimes as $name => $value ) {
322 if ( $info !== '' ) {
325 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
328 # IE sends sizes after the date like this:
329 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
330 # this breaks strtotime().
331 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
333 wfSuppressWarnings(); // E_STRICT system time bitching
334 $clientHeaderTime = strtotime( $clientHeader );
336 if ( !$clientHeaderTime ) {
337 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
340 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
342 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
343 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
344 wfDebug( __METHOD__
. ": effective Last-Modified: " .
345 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
346 if( $clientHeaderTime < $maxModified ) {
347 wfDebug( __METHOD__
. ": STALE, $info\n", false );
352 # Give a 304 response code and disable body output
353 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
354 ini_set('zlib.output_compression', 0);
355 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
356 $this->sendCacheControl();
359 // Don't output a compressed blob when using ob_gzhandler;
360 // it's technically against HTTP spec and seems to confuse
361 // Firefox when the response gets split over two packets.
362 wfClearOutputBuffers();
369 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
371 * @param $policy String: the literal string to output as the contents of
372 * the meta tag. Will be parsed according to the spec and output in
376 public function setRobotPolicy( $policy ) {
377 $policy = Article
::formatRobotPolicy( $policy );
379 if( isset( $policy['index'] ) ){
380 $this->setIndexPolicy( $policy['index'] );
382 if( isset( $policy['follow'] ) ){
383 $this->setFollowPolicy( $policy['follow'] );
388 * Set the index policy for the page, but leave the follow policy un-
391 * @param $policy string Either 'index' or 'noindex'.
394 public function setIndexPolicy( $policy ) {
395 $policy = trim( $policy );
396 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
397 $this->mIndexPolicy
= $policy;
402 * Set the follow policy for the page, but leave the index policy un-
405 * @param $policy String: either 'follow' or 'nofollow'.
408 public function setFollowPolicy( $policy ) {
409 $policy = trim( $policy );
410 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
411 $this->mFollowPolicy
= $policy;
417 * Set the new value of the "action text", this will be added to the
418 * "HTML title", separated from it with " - ".
420 * @param $text String: new value of the "action text"
422 public function setPageTitleActionText( $text ) {
423 $this->mPageTitleActionText
= $text;
427 * Get the value of the "action text"
431 public function getPageTitleActionText() {
432 if ( isset( $this->mPageTitleActionText
) ) {
433 return $this->mPageTitleActionText
;
438 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
440 public function setHTMLTitle( $name ) {
441 $this->mHTMLtitle
= $name;
445 * Return the "HTML title", i.e. the content of the <title> tag.
449 public function getHTMLTitle() {
450 return $this->mHTMLtitle
;
454 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
455 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
456 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
457 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
459 public function setPageTitle( $name ) {
460 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
461 # but leave "<i>foobar</i>" alone
462 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
463 $this->mPagetitle
= $nameWithTags;
465 $taction = $this->getPageTitleActionText();
466 if( !empty( $taction ) ) {
467 $name .= ' - '.$taction;
470 # change "<i>foo&bar</i>" to "foo&bar"
471 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
475 * Return the "page title", i.e. the content of the <h1> tag.
479 public function getPageTitle() {
480 return $this->mPagetitle
;
484 * Set the Title object to use
486 * @param $t Title object
488 public function setTitle( $t ) {
493 * Get the Title object used in this instance
497 public function getTitle() {
498 if ( $this->mTitle
instanceof Title
) {
499 return $this->mTitle
;
501 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
508 * Replace the subtile with $str
510 * @param $str String: new value of the subtitle
512 public function setSubtitle( $str ) {
513 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
517 * Add $str to the subtitle
519 * @param $str String to add to the subtitle
521 public function appendSubtitle( $str ) {
522 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
530 public function getSubtitle() {
531 return $this->mSubtitle
;
536 * Set the page as printable, i.e. it'll be displayed with with all
537 * print styles included
539 public function setPrintable() {
540 $this->mPrintable
= true;
544 * Return whether the page is "printable"
548 public function isPrintable() {
549 return $this->mPrintable
;
554 * Disable output completely, i.e. calling output() will have no effect
556 public function disable() {
557 $this->mDoNothing
= true;
561 * Return whether the output will be completely disabled
565 public function isDisabled() {
566 return $this->mDoNothing
;
571 * Add or remove feed links in the page header
572 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
573 * for the new version
576 * @param $show Boolean: true: add default feeds, false: remove all feeds
578 public function setSyndicated( $show = true ) {
580 $this->setFeedAppendQuery( false );
582 $this->mFeedLinks
= array();
587 * Add default feeds to the page header
588 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
589 * for the new version
592 * @param $val String: query to append to feed links or false to output
595 public function setFeedAppendQuery( $val ) {
596 global $wgAdvertisedFeedTypes;
598 $this->mFeedLinks
= array();
600 foreach ( $wgAdvertisedFeedTypes as $type ) {
601 $query = "feed=$type";
602 if ( is_string( $val ) ) {
603 $query .= '&' . $val;
605 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
610 * Add a feed link to the page header
612 * @param $format String: feed type, should be a key of $wgFeedClasses
613 * @param $href String: URL
615 public function addFeedLink( $format, $href ) {
616 $this->mFeedLinks
[$format] = $href;
620 * Should we output feed links for this page?
623 public function isSyndicated() {
624 return count( $this->mFeedLinks
) > 0;
628 * Will currently always return null
632 public function getFeedAppendQuery() {
633 return $this->mFeedLinksAppendQuery
;
637 * Set whether the displayed content is related to the source of the
638 * corresponding article on the wiki
639 * Setting true will cause the change "article related" toggle to true
643 public function setArticleFlag( $v ) {
644 $this->mIsarticle
= $v;
646 $this->mIsArticleRelated
= $v;
651 * Return whether the content displayed page is related to the source of
652 * the corresponding article on the wiki
656 public function isArticle() {
657 return $this->mIsarticle
;
661 * Set whether this page is related an article on the wiki
662 * Setting false will cause the change of "article flag" toggle to false
666 public function setArticleRelated( $v ) {
667 $this->mIsArticleRelated
= $v;
669 $this->mIsarticle
= false;
674 * Return whether this page is related an article on the wiki
678 public function isArticleRelated() {
679 return $this->mIsArticleRelated
;
684 * Add new language links
686 * @param $newLinkArray Associative array mapping language code to the page
689 public function addLanguageLinks( $newLinkArray ) {
690 $this->mLanguageLinks +
= $newLinkArray;
694 * Reset the language links and add new language links
696 * @param $newLinkArray Associative array mapping language code to the page
699 public function setLanguageLinks( $newLinkArray ) {
700 $this->mLanguageLinks
= $newLinkArray;
704 * Get the list of language links
706 * @return Associative array mapping language code to the page name
708 public function getLanguageLinks() {
709 return $this->mLanguageLinks
;
714 * Add an array of categories, with names in the keys
716 * @param $categories Associative array mapping category name to its sort key
718 public function addCategoryLinks( $categories ) {
719 global $wgUser, $wgContLang;
721 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
725 # Add the links to a LinkBatch
726 $arr = array( NS_CATEGORY
=> $categories );
728 $lb->setArray( $arr );
730 # Fetch existence plus the hiddencat property
731 $dbr = wfGetDB( DB_SLAVE
);
732 $pageTable = $dbr->tableName( 'page' );
733 $where = $lb->constructSet( 'page', $dbr );
734 $propsTable = $dbr->tableName( 'page_props' );
735 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
736 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
737 $res = $dbr->query( $sql, __METHOD__
);
739 # Add the results to the link cache
740 $lb->addResultToCache( LinkCache
::singleton(), $res );
742 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
743 $categories = array_combine( array_keys( $categories ),
744 array_fill( 0, count( $categories ), 'normal' ) );
746 # Mark hidden categories
747 foreach ( $res as $row ) {
748 if ( isset( $row->pp_value
) ) {
749 $categories[$row->page_title
] = 'hidden';
753 # Add the remaining categories to the skin
754 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
755 $sk = $wgUser->getSkin();
756 foreach ( $categories as $category => $type ) {
757 $origcategory = $category;
758 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
759 $wgContLang->findVariantLink( $category, $title, true );
760 if ( $category != $origcategory )
761 if ( array_key_exists( $category, $categories ) )
763 $text = $wgContLang->convertHtml( $title->getText() );
764 $this->mCategories
[] = $title->getText();
765 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
771 * Reset the category links (but not the category list) and add $categories
773 * @param $categories Associative array mapping category name to its sort key
775 public function setCategoryLinks( $categories ) {
776 $this->mCategoryLinks
= array();
777 $this->addCategoryLinks( $categories );
781 * Get the list of category links, in a 2-D array with the following format:
782 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
783 * hidden categories) and $link a HTML fragment with a link to the category
788 public function getCategoryLinks() {
789 return $this->mCategoryLinks
;
793 * Get the list of category names this page belongs to
795 * @return Array of strings
797 public function getCategories() {
798 return $this->mCategories
;
801 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
802 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
804 public function disallowUserJs() { $this->mAllowUserJs
= false; }
805 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
807 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
808 public function addHTML( $text ) { $this->mBodytext
.= $text; }
809 public function clearHTML() { $this->mBodytext
= ''; }
810 public function getHTML() { return $this->mBodytext
; }
811 public function debug( $text ) { $this->mDebugtext
.= $text; }
814 public function setParserOptions( $options ) {
815 wfDeprecated( __METHOD__
);
816 return $this->parserOptions( $options );
819 public function parserOptions( $options = null ) {
820 if ( !$this->mParserOptions
) {
821 $this->mParserOptions
= new ParserOptions
;
823 return wfSetVar( $this->mParserOptions
, $options );
827 * Set the revision ID which will be seen by the wiki text parser
828 * for things such as embedded {{REVISIONID}} variable use.
829 * @param mixed $revid an integer, or NULL
830 * @return mixed previous value
832 public function setRevisionId( $revid ) {
833 $val = is_null( $revid ) ?
null : intval( $revid );
834 return wfSetVar( $this->mRevisionId
, $val );
837 public function getRevisionId() {
838 return $this->mRevisionId
;
842 * Convert wikitext to HTML and add it to the buffer
843 * Default assumes that the current page title will
846 * @param string $text
847 * @param bool $linestart
849 public function addWikiText( $text, $linestart = true ) {
850 $title = $this->getTitle(); // Work arround E_STRICT
851 $this->addWikiTextTitle( $text, $title, $linestart );
854 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
855 $this->addWikiTextTitle($text, $title, $linestart);
858 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
859 $this->addWikiTextTitle( $text, $title, $linestart, true );
862 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
865 wfProfileIn( __METHOD__
);
867 wfIncrStats( 'pcache_not_possible' );
869 $popts = $this->parserOptions();
870 $oldTidy = $popts->setTidy( $tidy );
872 $parserOutput = $wgParser->parse( $text, $title, $popts,
873 $linestart, true, $this->mRevisionId
);
875 $popts->setTidy( $oldTidy );
877 $this->addParserOutput( $parserOutput );
879 wfProfileOut( __METHOD__
);
884 * @param ParserOutput object &$parserOutput
886 public function addParserOutputNoText( &$parserOutput ) {
887 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
889 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
890 $this->addCategoryLinks( $parserOutput->getCategories() );
891 $this->mNewSectionLink
= $parserOutput->getNewSection();
892 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
894 $this->mParseWarnings
= $parserOutput->getWarnings();
895 if ( $parserOutput->getCacheTime() == -1 ) {
896 $this->enableClientCache( false );
898 $this->mNoGallery
= $parserOutput->getNoGallery();
899 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
901 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
902 if ( isset( $this->mTemplateIds
[$ns] ) ) {
903 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
905 $this->mTemplateIds
[$ns] = $dbks;
909 $title = $parserOutput->getTitleText();
910 if ( $title != '' ) {
911 $this->setPageTitle( $title );
914 // Hooks registered in the object
915 global $wgParserOutputHooks;
916 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
917 list( $hookName, $data ) = $hookInfo;
918 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
919 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
923 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
928 * @param ParserOutput &$parserOutput
930 function addParserOutput( &$parserOutput ) {
931 $this->addParserOutputNoText( $parserOutput );
932 $text = $parserOutput->getText();
933 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
934 $this->addHTML( $text );
938 * Add wikitext to the buffer, assuming that this is the primary text for a page view
939 * Saves the text into the parser cache if possible.
941 * @param string $text
942 * @param Article $article
944 * @deprecated Use Article::outputWikitext
946 public function addPrimaryWikiText( $text, $article, $cache = true ) {
949 wfDeprecated( __METHOD__
);
951 $popts = $this->parserOptions();
952 $popts->setTidy(true);
953 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
954 $popts, true, true, $this->mRevisionId
);
955 $popts->setTidy(false);
956 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
957 $parserCache = ParserCache
::singleton();
958 $parserCache->save( $parserOutput, $article, $popts);
961 $this->addParserOutput( $parserOutput );
965 * @deprecated use addWikiTextTidy()
967 public function addSecondaryWikiText( $text, $linestart = true ) {
968 wfDeprecated( __METHOD__
);
969 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
973 * Add wikitext with tidy enabled
975 public function addWikiTextTidy( $text, $linestart = true ) {
976 $title = $this->getTitle();
977 $this->addWikiTextTitleTidy($text, $title, $linestart);
982 * Add the output of a QuickTemplate to the output buffer
984 * @param QuickTemplate $template
986 public function addTemplate( &$template ) {
988 $template->execute();
989 $this->addHTML( ob_get_contents() );
994 * Parse wikitext and return the HTML.
996 * @param string $text
997 * @param bool $linestart Is this the start of a line?
998 * @param bool $interface ??
1000 public function parse( $text, $linestart = true, $interface = false ) {
1002 if( is_null( $this->getTitle() ) ) {
1003 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1005 $popts = $this->parserOptions();
1006 if ( $interface) { $popts->setInterfaceMessage(true); }
1007 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
1008 $linestart, true, $this->mRevisionId
);
1009 if ( $interface) { $popts->setInterfaceMessage(false); }
1010 return $parserOutput->getText();
1013 /** Parse wikitext, strip paragraphs, and return the HTML. */
1014 public function parseInline( $text, $linestart = true, $interface = false ) {
1015 $parsed = $this->parse( $text, $linestart, $interface );
1018 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1026 * @param Article $article
1031 * @return bool True if successful, else false.
1033 public function tryParserCache( &$article ) {
1034 wfDeprecated( __METHOD__
);
1035 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
1037 if ($parserOutput !== false) {
1038 $this->addParserOutput( $parserOutput );
1046 * @param int $maxage Maximum cache time on the Squid, in seconds.
1048 public function setSquidMaxage( $maxage ) {
1049 $this->mSquidMaxage
= $maxage;
1053 * Use enableClientCache(false) to force it to send nocache headers
1056 public function enableClientCache( $state ) {
1057 return wfSetVar( $this->mEnableClientCache
, $state );
1060 function getCacheVaryCookies() {
1061 global $wgCookiePrefix, $wgCacheVaryCookies;
1063 if ( $cookies === null ) {
1064 $cookies = array_merge(
1066 "{$wgCookiePrefix}Token",
1067 "{$wgCookiePrefix}LoggedOut",
1072 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
1077 function uncacheableBecauseRequestVars() {
1079 return $wgRequest->getText('useskin', false) === false
1080 && $wgRequest->getText('uselang', false) === false;
1084 * Check if the request has a cache-varying cookie header
1085 * If it does, it's very important that we don't allow public caching
1087 function haveCacheVaryCookies() {
1089 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1090 if ( $cookieHeader === false ) {
1093 $cvCookies = $this->getCacheVaryCookies();
1094 foreach ( $cvCookies as $cookieName ) {
1095 # Check for a simple string match, like the way squid does it
1096 if ( strpos( $cookieHeader, $cookieName ) ) {
1097 wfDebug( __METHOD__
.": found $cookieName\n" );
1101 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
1105 public function addVaryHeader( $header, $option = null ) {
1106 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1107 $this->mVaryHeader
[$header] = $option;
1109 elseif( is_array( $option ) ) {
1110 if( is_array( $this->mVaryHeader
[$header] ) ) {
1111 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1114 $this->mVaryHeader
[$header] = $option;
1117 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1120 /** Get a complete X-Vary-Options header */
1121 public function getXVO() {
1122 $cvCookies = $this->getCacheVaryCookies();
1124 $cookiesOption = array();
1125 foreach ( $cvCookies as $cookieName ) {
1126 $cookiesOption[] = 'string-contains=' . $cookieName;
1128 $this->addVaryHeader( 'Cookie', $cookiesOption );
1131 foreach( $this->mVaryHeader
as $header => $option ) {
1132 $newheader = $header;
1133 if( is_array( $option ) )
1134 $newheader .= ';' . implode( ';', $option );
1135 $headers[] = $newheader;
1137 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1142 /** bug 21672: Add Accept-Language to Vary and XVO headers
1143 if there's no 'variant' parameter existed in GET.
1146 /w/index.php?title=Main_page should always be served; but
1147 /w/index.php?title=Main_page&variant=zh-cn should never be served.
1149 patched by Liangent and Philip */
1150 function addAcceptLanguage() {
1151 global $wgRequest, $wgContLang;
1152 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
1153 $variants = $wgContLang->getVariants();
1154 $aloption = array();
1155 foreach ( $variants as $variant ) {
1156 if( $variant === $wgContLang->getCode() )
1159 $aloption[] = "string-contains=$variant";
1161 $this->addVaryHeader( 'Accept-Language', $aloption );
1165 public function sendCacheControl() {
1166 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1168 $response = $wgRequest->response();
1169 if ($wgUseETag && $this->mETag
)
1170 $response->header("ETag: $this->mETag");
1172 $this->addAcceptLanguage();
1174 # don't serve compressed data to clients who can't handle it
1175 # maintain different caches for logged-in users and non-logged in ones
1176 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1179 # Add an X-Vary-Options header for Squid with Wikimedia patches
1180 $response->header( $this->getXVO() );
1183 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1184 if( $wgUseSquid && session_id() == '' &&
1185 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1188 # We'll purge the proxy cache explicitly, but require end user agents
1189 # to revalidate against the proxy on each visit.
1190 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1191 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1192 # start with a shorter timeout for initial testing
1193 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1194 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1195 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1197 # We'll purge the proxy cache for anons explicitly, but require end user agents
1198 # to revalidate against the proxy on each visit.
1199 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1200 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1201 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1202 # start with a shorter timeout for initial testing
1203 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1204 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1207 # We do want clients to cache if they can, but they *must* check for updates
1208 # on revisiting the page.
1209 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1210 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1211 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1213 if($this->mLastModified
) {
1214 $response->header( "Last-Modified: {$this->mLastModified}" );
1217 wfDebug( __METHOD__
. ": no caching **\n", false );
1219 # In general, the absence of a last modified header should be enough to prevent
1220 # the client from using its cache. We send a few other things just to make sure.
1221 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1222 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1223 $response->header( 'Pragma: no-cache' );
1225 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
1229 * Get the message associed with the HTTP response code $code
1231 * @param $code Integer: status code
1232 * @return String or null: message or null if $code is not in the list of
1235 public static function getStatusMessage( $code ) {
1236 static $statusMessage = array(
1238 101 => 'Switching Protocols',
1239 102 => 'Processing',
1243 203 => 'Non-Authoritative Information',
1244 204 => 'No Content',
1245 205 => 'Reset Content',
1246 206 => 'Partial Content',
1247 207 => 'Multi-Status',
1248 300 => 'Multiple Choices',
1249 301 => 'Moved Permanently',
1252 304 => 'Not Modified',
1254 307 => 'Temporary Redirect',
1255 400 => 'Bad Request',
1256 401 => 'Unauthorized',
1257 402 => 'Payment Required',
1260 405 => 'Method Not Allowed',
1261 406 => 'Not Acceptable',
1262 407 => 'Proxy Authentication Required',
1263 408 => 'Request Timeout',
1266 411 => 'Length Required',
1267 412 => 'Precondition Failed',
1268 413 => 'Request Entity Too Large',
1269 414 => 'Request-URI Too Large',
1270 415 => 'Unsupported Media Type',
1271 416 => 'Request Range Not Satisfiable',
1272 417 => 'Expectation Failed',
1273 422 => 'Unprocessable Entity',
1275 424 => 'Failed Dependency',
1276 500 => 'Internal Server Error',
1277 501 => 'Not Implemented',
1278 502 => 'Bad Gateway',
1279 503 => 'Service Unavailable',
1280 504 => 'Gateway Timeout',
1281 505 => 'HTTP Version Not Supported',
1282 507 => 'Insufficient Storage'
1284 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1288 * Finally, all the text has been munged and accumulated into
1289 * the object, let's actually output it:
1291 public function output() {
1292 global $wgUser, $wgOutputEncoding, $wgRequest;
1293 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1294 global $wgUseAjax, $wgAjaxWatch;
1295 global $wgEnableMWSuggest, $wgUniversalEditButton;
1298 if( $this->mDoNothing
){
1301 wfProfileIn( __METHOD__
);
1302 if ( $this->mRedirect
!= '' ) {
1303 # Standards require redirect URLs to be absolute
1304 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1305 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1306 if( !$wgDebugRedirects ) {
1307 $message = self
::getStatusMessage( $this->mRedirectCode
);
1308 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1310 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1312 $this->sendCacheControl();
1314 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1315 if( $wgDebugRedirects ) {
1316 $url = htmlspecialchars( $this->mRedirect
);
1317 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1318 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1319 print "</body>\n</html>\n";
1321 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1323 wfProfileOut( __METHOD__
);
1325 } elseif ( $this->mStatusCode
) {
1326 $message = self
::getStatusMessage( $this->mStatusCode
);
1328 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1331 $sk = $wgUser->getSkin();
1334 $this->addScriptFile( 'ajax.js' );
1336 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1338 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1339 $this->addScriptFile( 'ajaxwatch.js' );
1342 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1343 $this->addScriptFile( 'mwsuggest.js' );
1347 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1348 $this->addScriptFile( 'rightclickedit.js' );
1351 if( $wgUniversalEditButton ) {
1352 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1353 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1354 // Original UniversalEditButton
1355 $msg = wfMsg('edit');
1356 $this->addLink( array(
1357 'rel' => 'alternate',
1358 'type' => 'application/x-wiki',
1360 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1362 // Alternate edit link
1363 $this->addLink( array(
1366 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1371 # Buffer output; final headers may depend on later processing
1374 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1375 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1377 if ($this->mArticleBodyOnly
) {
1378 $this->out($this->mBodytext
);
1380 // Hook that allows last minute changes to the output page, e.g.
1381 // adding of CSS or Javascript by extensions.
1382 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1384 wfProfileIn( 'Output-skin' );
1385 $sk->outputPage( $this );
1386 wfProfileOut( 'Output-skin' );
1389 $this->sendCacheControl();
1391 wfProfileOut( __METHOD__
);
1395 * Actually output something with print(). Performs an iconv to the
1396 * output encoding, if needed.
1397 * @param string $ins The string to output
1399 public function out( $ins ) {
1400 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1401 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1404 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1405 if ( false === $outs ) { $outs = $ins; }
1413 public static function setEncodings() {
1414 global $wgInputEncoding, $wgOutputEncoding;
1417 $wgInputEncoding = strtolower( $wgInputEncoding );
1419 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1420 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1423 $wgOutputEncoding = $wgInputEncoding;
1427 * Deprecated, use wfReportTime() instead.
1431 public function reportTime() {
1432 wfDeprecated( __METHOD__
);
1433 $time = wfReportTime();
1438 * Produce a "user is blocked" page.
1440 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1443 function blockedPage( $return = true ) {
1444 global $wgUser, $wgContLang, $wgLang;
1446 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1447 $this->setRobotPolicy( 'noindex,nofollow' );
1448 $this->setArticleRelated( false );
1450 $name = User
::whoIs( $wgUser->blockedBy() );
1451 $reason = $wgUser->blockedFor();
1452 if( $reason == '' ) {
1453 $reason = wfMsg( 'blockednoreason' );
1455 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1458 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1460 $blockid = $wgUser->mBlock
->mId
;
1462 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1463 if ( $blockExpiry == 'infinity' ) {
1464 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1465 // Search for localization in 'ipboptions'
1466 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1467 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1468 if ( strpos( $option, ":" ) === false )
1470 list( $show, $value ) = explode( ":", $option );
1471 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1472 $blockExpiry = $show;
1477 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1480 if ( $wgUser->mBlock
->mAuto
) {
1481 $msg = 'autoblockedtext';
1483 $msg = 'blockedtext';
1486 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1487 * This could be a username, an ip range, or a single ip. */
1488 $intended = $wgUser->mBlock
->mAddress
;
1490 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1492 # Don't auto-return to special pages
1494 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1495 $this->returnToMain( null, $return );
1500 * Output a standard error page
1502 * @param string $title Message key for page title
1503 * @param string $msg Message key for page text
1504 * @param array $params Message parameters
1506 public function showErrorPage( $title, $msg, $params = array() ) {
1507 if ( $this->getTitle() ) {
1508 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1510 $this->setPageTitle( wfMsg( $title ) );
1511 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1512 $this->setRobotPolicy( 'noindex,nofollow' );
1513 $this->setArticleRelated( false );
1514 $this->enableClientCache( false );
1515 $this->mRedirect
= '';
1516 $this->mBodytext
= '';
1518 array_unshift( $params, 'parse' );
1519 array_unshift( $params, $msg );
1520 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1522 $this->returnToMain();
1526 * Output a standard permission error page
1528 * @param array $errors Error message keys
1530 public function showPermissionsErrorPage( $errors, $action = null )
1532 $this->mDebugtext
.= 'Original title: ' .
1533 $this->getTitle()->getPrefixedText() . "\n";
1534 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1535 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1536 $this->setRobotPolicy( 'noindex,nofollow' );
1537 $this->setArticleRelated( false );
1538 $this->enableClientCache( false );
1539 $this->mRedirect
= '';
1540 $this->mBodytext
= '';
1541 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1545 public function errorpage( $title, $msg ) {
1546 wfDeprecated( __METHOD__
);
1547 throw new ErrorPageError( $title, $msg );
1551 * Display an error page indicating that a given version of MediaWiki is
1552 * required to use it
1554 * @param mixed $version The version of MediaWiki needed to use the page
1556 public function versionRequired( $version ) {
1557 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1558 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1559 $this->setRobotPolicy( 'noindex,nofollow' );
1560 $this->setArticleRelated( false );
1561 $this->mBodytext
= '';
1563 $this->addWikiMsg( 'versionrequiredtext', $version );
1564 $this->returnToMain();
1568 * Display an error page noting that a given permission bit is required.
1570 * @param string $permission key required
1572 public function permissionRequired( $permission ) {
1575 $this->setPageTitle( wfMsg( 'badaccess' ) );
1576 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1577 $this->setRobotPolicy( 'noindex,nofollow' );
1578 $this->setArticleRelated( false );
1579 $this->mBodytext
= '';
1581 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1582 User
::getGroupsWithPermission( $permission ) );
1584 $this->addWikiMsg( 'badaccess-groups',
1585 $wgLang->commaList( $groups ),
1588 $this->addWikiMsg( 'badaccess-group0' );
1590 $this->returnToMain();
1594 * Use permissionRequired.
1597 public function sysopRequired() {
1598 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1602 * Use permissionRequired.
1605 public function developerRequired() {
1606 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1610 * Produce the stock "please login to use the wiki" page
1612 public function loginToUse() {
1613 global $wgUser, $wgContLang;
1615 if( $wgUser->isLoggedIn() ) {
1616 $this->permissionRequired( 'read' );
1620 $skin = $wgUser->getSkin();
1622 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1623 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1624 $this->setRobotPolicy( 'noindex,nofollow' );
1625 $this->setArticleFlag( false );
1627 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1628 $loginLink = $skin->link(
1630 wfMsgHtml( 'loginreqlink' ),
1632 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1633 array( 'known', 'noclasses' )
1635 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1636 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1638 # Don't return to the main page if the user can't read it
1639 # otherwise we'll end up in a pointless loop
1640 $mainPage = Title
::newMainPage();
1641 if( $mainPage->userCanRead() )
1642 $this->returnToMain( null, $mainPage );
1646 public function databaseError( $fname, $sql, $error, $errno ) {
1647 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1651 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1652 * @return string The wikitext error-messages, formatted into a list.
1654 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1655 if ($action == null) {
1656 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1659 $action_desc = wfMsgNoTrans( "action-$action" );
1660 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1663 if (count( $errors ) > 1) {
1664 $text .= '<ul class="permissions-errors">' . "\n";
1666 foreach( $errors as $error )
1669 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1674 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1681 * Display a page stating that the Wiki is in read-only mode,
1682 * and optionally show the source of the page that the user
1683 * was trying to edit. Should only be called (for this
1684 * purpose) after wfReadOnly() has returned true.
1686 * For historical reasons, this function is _also_ used to
1687 * show the error message when a user tries to edit a page
1688 * they are not allowed to edit. (Unless it's because they're
1689 * blocked, then we show blockedPage() instead.) In this
1690 * case, the second parameter should be set to true and a list
1691 * of reasons supplied as the third parameter.
1693 * @todo Needs to be split into multiple functions.
1695 * @param string $source Source code to show (or null).
1696 * @param bool $protected Is this a permissions error?
1697 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1699 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1701 $skin = $wgUser->getSkin();
1703 $this->setRobotPolicy( 'noindex,nofollow' );
1704 $this->setArticleRelated( false );
1706 // If no reason is given, just supply a default "I can't let you do
1707 // that, Dave" message. Should only occur if called by legacy code.
1708 if ( $protected && empty($reasons) ) {
1709 $reasons[] = array( 'badaccess-group0' );
1712 if ( !empty($reasons) ) {
1713 // Permissions error
1715 $this->setPageTitle( wfMsg( 'viewsource' ) );
1724 array( 'known', 'noclasses' )
1729 $this->setPageTitle( wfMsg( 'badaccess' ) );
1731 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1733 // Wiki is read only
1734 $this->setPageTitle( wfMsg( 'readonly' ) );
1735 $reason = wfReadOnlyReason();
1736 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1739 // Show source, if supplied
1740 if( is_string( $source ) ) {
1741 $this->addWikiMsg( 'viewsourcetext' );
1744 'id' => 'wpTextbox1',
1745 'name' => 'wpTextbox1',
1746 'cols' => $wgUser->getOption( 'cols' ),
1747 'rows' => $wgUser->getOption( 'rows' ),
1748 'readonly' => 'readonly'
1750 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1752 // Show templates used by this article
1753 $skin = $wgUser->getSkin();
1754 $article = new Article( $this->getTitle() );
1755 $this->addHTML( "<div class='templatesUsed'>
1756 {$skin->formatTemplates( $article->getUsedTemplates() )}
1761 # If the title doesn't exist, it's fairly pointless to print a return
1762 # link to it. After all, you just tried editing it and couldn't, so
1763 # what's there to do there?
1764 if( $this->getTitle()->exists() ) {
1765 $this->returnToMain( null, $this->getTitle() );
1770 public function fatalError( $message ) {
1771 wfDeprecated( __METHOD__
);
1772 throw new FatalError( $message );
1776 public function unexpectedValueError( $name, $val ) {
1777 wfDeprecated( __METHOD__
);
1778 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1782 public function fileCopyError( $old, $new ) {
1783 wfDeprecated( __METHOD__
);
1784 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1788 public function fileRenameError( $old, $new ) {
1789 wfDeprecated( __METHOD__
);
1790 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1794 public function fileDeleteError( $name ) {
1795 wfDeprecated( __METHOD__
);
1796 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1800 public function fileNotFoundError( $name ) {
1801 wfDeprecated( __METHOD__
);
1802 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1805 public function showFatalError( $message ) {
1806 $this->setPageTitle( wfMsg( "internalerror" ) );
1807 $this->setRobotPolicy( "noindex,nofollow" );
1808 $this->setArticleRelated( false );
1809 $this->enableClientCache( false );
1810 $this->mRedirect
= '';
1811 $this->mBodytext
= $message;
1814 public function showUnexpectedValueError( $name, $val ) {
1815 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1818 public function showFileCopyError( $old, $new ) {
1819 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1822 public function showFileRenameError( $old, $new ) {
1823 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1826 public function showFileDeleteError( $name ) {
1827 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1830 public function showFileNotFoundError( $name ) {
1831 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1835 * Add a "return to" link pointing to a specified title
1837 * @param $title Title to link
1838 * @param $query String: query string
1840 public function addReturnTo( $title, $query = array() ) {
1842 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1843 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1844 $title, null, array(), $query ) );
1845 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1849 * Add a "return to" link pointing to a specified title,
1850 * or the title indicated in the request, or else the main page
1852 * @param $unused No longer used
1853 * @param $returnto Title or String to return to
1854 * @param $returntoquery String: query string for the return to link
1856 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1859 if ( $returnto == null ) {
1860 $returnto = $wgRequest->getText( 'returnto' );
1863 if ( $returntoquery == null ) {
1864 $returntoquery = $wgRequest->getText( 'returntoquery' );
1867 if ( $returnto === '' ) {
1868 $returnto = Title
::newMainPage();
1871 if ( is_object( $returnto ) ) {
1872 $titleObj = $returnto;
1874 $titleObj = Title
::newFromText( $returnto );
1876 if ( !is_object( $titleObj ) ) {
1877 $titleObj = Title
::newMainPage();
1880 $this->addReturnTo( $titleObj, $returntoquery );
1884 * @return string The doctype, opening <html>, and head element.
1886 * @param $sk Skin The given Skin
1888 public function headElement( Skin
$sk, $includeStyle = true ) {
1889 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1890 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1891 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1892 global $wgUser, $wgRequest, $wgLang;
1894 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1895 if ( $sk->commonPrintStylesheet() ) {
1896 $this->addStyle( 'common/wikiprintable.css', 'print' );
1898 $sk->setupUserCss( $this );
1902 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1903 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1906 if ( $this->getHTMLTitle() == '' ) {
1907 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1910 $dir = $wgContLang->getDir();
1913 if ( $wgWellFormedXml ) {
1914 # Unknown elements and attributes are okay in XML, but unknown
1915 # named entities are well-formedness errors and will break XML
1916 # parsers. Thus we need a doctype that gives us appropriate
1917 # entity definitions. The HTML5 spec permits four legacy
1918 # doctypes as obsolete but conforming, so let's pick one of
1919 # those, although it makes our pages look like XHTML1 Strict.
1920 # Isn't compatibility great?
1921 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1924 $ret .= "<!doctype html>\n";
1926 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1927 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1930 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1931 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1932 foreach($wgXhtmlNamespaces as $tag => $ns) {
1933 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1935 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1939 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1940 $ret .= implode( "\n", array(
1941 $this->getHeadLinks(),
1942 $this->buildCssLinks(),
1943 $this->getHeadScripts( $sk ),
1944 $this->getHeadItems(),
1947 $ret .= Html
::inlineStyle( $sk->usercss
);
1950 if ($wgUseTrackbacks && $this->isArticleRelated())
1951 $ret .= $this->getTitle()->trackbackRDF();
1953 $ret .= "</head>\n";
1955 $bodyAttrs = array();
1957 # Crazy edit-on-double-click stuff
1958 $action = $wgRequest->getVal( 'action', 'view' );
1960 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
1961 && !in_array( $action, array( 'edit', 'submit' ) )
1962 && $wgUser->getOption( 'editondblclick' ) ) {
1963 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
1967 $bodyAttrs['class'] = "mediawiki $dir";
1969 if ( $wgLang->capitalizeAllNouns() ) {
1970 # A <body> class is probably not the best way to do this . . .
1971 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1973 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
1974 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
1975 $bodyAttrs['class'] .= ' ns-special';
1976 } elseif ( $this->getTitle()->isTalkPage() ) {
1977 $bodyAttrs['class'] .= ' ns-talk';
1979 $bodyAttrs['class'] .= ' ns-subject';
1981 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
1982 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
1984 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
1990 * gets the global variables and mScripts
1992 * also adds userjs to the end if enabled:
1994 function getHeadScripts( Skin
$sk ) {
1995 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1996 global $wgStylePath, $wgStyleVersion;
1998 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1999 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
2001 //add site JS if enabled:
2002 if( $wgUseSiteJs ) {
2003 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
2004 $this->addScriptFile( Skin
::makeUrl( '-',
2005 "action=raw$jsCache&gen=js&useskin=" .
2006 urlencode( $sk->getSkinName() )
2011 //add user js if enabled:
2012 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2013 $action = $wgRequest->getVal( 'action', 'view' );
2014 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
2015 # XXX: additional security check/prompt?
2016 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2018 $userpage = $wgUser->getUserPage();
2019 $scriptpage = Title
::makeTitleSafe(
2021 $userpage->getDBkey() . '/' . $sk->getSkinName() . '.js'
2023 if ( $scriptpage && $scriptpage->exists() ) {
2024 $userjs = Skin
::makeUrl( $scriptpage->getPrefixedText(), 'action=raw&ctype=' . $wgJsMimeType );
2025 $this->addScriptFile( $userjs );
2030 $scripts .= "\n" . $this->mScripts
;
2034 protected function addDefaultMeta() {
2035 global $wgVersion, $wgHtml5;
2037 static $called = false;
2039 # Don't run this twice
2045 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
2047 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2049 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2050 if( $p !== 'index,follow' ) {
2051 // http://www.robotstxt.org/wc/meta-user.html
2052 // Only show if it's different from the default robots policy
2053 $this->addMeta( 'robots', $p );
2056 if ( count( $this->mKeywords
) > 0 ) {
2058 "/<.*?" . ">/" => '',
2061 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
2066 * @return string HTML tag links to be put in the header.
2068 public function getHeadLinks() {
2069 global $wgRequest, $wgFeed;
2071 // Ideally this should happen earlier, somewhere. :P
2072 $this->addDefaultMeta();
2076 foreach ( $this->mMetatags
as $tag ) {
2077 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2079 $tag[0] = substr( $tag[0], 5 );
2083 $tags[] = Html
::element( 'meta',
2086 'content' => $tag[1] ) );
2088 foreach ( $this->mLinktags
as $tag ) {
2089 $tags[] = Html
::element( 'link', $tag );
2093 foreach( $this->getSyndicationLinks() as $format => $link ) {
2094 # Use the page name for the title (accessed through $wgTitle since
2095 # there's no other way). In principle, this could lead to issues
2096 # with having the same name for different feeds corresponding to
2097 # the same page, but we can't avoid that at this low a level.
2099 $tags[] = $this->feedLink(
2102 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2103 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
2106 # Recent changes feed should appear on every page (except recentchanges,
2107 # that would be redundant). Put it after the per-page feed to avoid
2108 # changing existing behavior. It's still available, probably via a
2109 # menu in your browser. Some sites might have a different feed they'd
2110 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2111 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2112 # If so, use it instead.
2114 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2115 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2117 if ( $wgOverrideSiteFeed ) {
2118 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2119 $tags[] = $this->feedLink (
2121 htmlspecialchars( $feedUrl ),
2122 wfMsg( "site-{$type}-feed", $wgSitename ) );
2124 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2125 foreach ( $wgAdvertisedFeedTypes as $format ) {
2126 $tags[] = $this->feedLink(
2128 $rctitle->getLocalURL( "feed={$format}" ),
2129 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
2134 return implode( "\n", $tags );
2138 * Return URLs for each supported syndication format for this page.
2139 * @return array associating format keys with URLs
2141 public function getSyndicationLinks() {
2142 return $this->mFeedLinks
;
2146 * Generate a <link rel/> for an RSS feed.
2148 private function feedLink( $type, $url, $text ) {
2149 return Html
::element( 'link', array(
2150 'rel' => 'alternate',
2151 'type' => "application/$type+xml",
2157 * Add a local or specified stylesheet, with the given media options.
2158 * Meant primarily for internal use...
2160 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
2161 * @param $conditional -- for IE conditional comments, specifying an IE version
2162 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
2164 public function addStyle( $style, $media='', $condition='', $dir='' ) {
2166 // Even though we expect the media type to be lowercase, but here we
2167 // force it to lowercase to be safe.
2169 $options['media'] = $media;
2171 $options['condition'] = $condition;
2173 $options['dir'] = $dir;
2174 $this->styles
[$style] = $options;
2178 * Adds inline CSS styles
2179 * @param $style_css Mixed: inline CSS
2181 public function addInlineStyle( $style_css ){
2182 $this->mScripts
.= Html
::inlineStyle( $style_css );
2186 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2187 * These will be applied to various media & IE conditionals.
2189 public function buildCssLinks() {
2191 foreach( $this->styles
as $file => $options ) {
2192 $link = $this->styleLink( $file, $options );
2197 return implode( "\n", $links );
2200 protected function styleLink( $style, $options ) {
2203 if( isset( $options['dir'] ) ) {
2205 $siteDir = $wgContLang->getDir();
2206 if( $siteDir != $options['dir'] )
2210 if( isset( $options['media'] ) ) {
2211 $media = $this->transformCssMedia( $options['media'] );
2212 if( is_null( $media ) ) {
2219 if( substr( $style, 0, 1 ) == '/' ||
2220 substr( $style, 0, 5 ) == 'http:' ||
2221 substr( $style, 0, 6 ) == 'https:' ) {
2224 global $wgStylePath, $wgStyleVersion;
2225 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2228 $link = Html
::linkedStyle( $url, $media );
2230 if( isset( $options['condition'] ) ) {
2231 $condition = htmlspecialchars( $options['condition'] );
2232 $link = "<!--[if $condition]>$link<![endif]-->";
2237 function transformCssMedia( $media ) {
2238 global $wgRequest, $wgHandheldForIPhone;
2240 // Switch in on-screen display for media testing
2242 'printable' => 'print',
2243 'handheld' => 'handheld',
2245 foreach( $switches as $switch => $targetMedia ) {
2246 if( $wgRequest->getBool( $switch ) ) {
2247 if( $media == $targetMedia ) {
2249 } elseif( $media == 'screen' ) {
2255 // Expand longer media queries as iPhone doesn't grok 'handheld'
2256 if( $wgHandheldForIPhone ) {
2257 $mediaAliases = array(
2258 'screen' => 'screen and (min-device-width: 481px)',
2259 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2262 if( isset( $mediaAliases[$media] ) ) {
2263 $media = $mediaAliases[$media];
2271 * Turn off regular page output and return an error reponse
2272 * for when rate limiting has triggered.
2274 public function rateLimited() {
2276 $this->setPageTitle(wfMsg('actionthrottled'));
2277 $this->setRobotPolicy( 'noindex,follow' );
2278 $this->setArticleRelated( false );
2279 $this->enableClientCache( false );
2280 $this->mRedirect
= '';
2282 $this->setStatusCode(503);
2283 $this->addWikiMsg( 'actionthrottledtext' );
2285 $this->returnToMain( null, $this->getTitle() );
2289 * Show an "add new section" link?
2293 public function showNewSectionLink() {
2294 return $this->mNewSectionLink
;
2298 * Forcibly hide the new section link?
2302 public function forceHideNewSectionLink() {
2303 return $this->mHideNewSectionLink
;
2307 * Show a warning about slave lag
2309 * If the lag is higher than $wgSlaveLagCritical seconds,
2310 * then the warning is a bit more obvious. If the lag is
2311 * lower than $wgSlaveLagWarning, then no warning is shown.
2313 * @param int $lag Slave lag
2315 public function showLagWarning( $lag ) {
2316 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2317 if( $lag >= $wgSlaveLagWarning ) {
2318 $message = $lag < $wgSlaveLagCritical
2321 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2322 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2327 * Add a wikitext-formatted message to the output.
2328 * This is equivalent to:
2330 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2332 public function addWikiMsg( /*...*/ ) {
2333 $args = func_get_args();
2334 $name = array_shift( $args );
2335 $this->addWikiMsgArray( $name, $args );
2339 * Add a wikitext-formatted message to the output.
2340 * Like addWikiMsg() except the parameters are taken as an array
2341 * instead of a variable argument list.
2343 * $options is passed through to wfMsgExt(), see that function for details.
2345 public function addWikiMsgArray( $name, $args, $options = array() ) {
2346 $options[] = 'parse';
2347 $text = wfMsgExt( $name, $options, $args );
2348 $this->addHTML( $text );
2352 * This function takes a number of message/argument specifications, wraps them in
2353 * some overall structure, and then parses the result and adds it to the output.
2355 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2356 * on. The subsequent arguments may either be strings, in which case they are the
2357 * message names, or arrays, in which case the first element is the message name,
2358 * and subsequent elements are the parameters to that message.
2360 * The special named parameter 'options' in a message specification array is passed
2361 * through to the $options parameter of wfMsgExt().
2363 * Don't use this for messages that are not in users interface language.
2367 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2371 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2373 * The newline after opening div is needed in some wikitext. See bug 19226.
2375 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2376 $msgSpecs = func_get_args();
2377 array_shift( $msgSpecs );
2378 $msgSpecs = array_values( $msgSpecs );
2380 foreach ( $msgSpecs as $n => $spec ) {
2382 if ( is_array( $spec ) ) {
2384 $name = array_shift( $args );
2385 if ( isset( $args['options'] ) ) {
2386 $options = $args['options'];
2387 unset( $args['options'] );
2393 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2395 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2399 * Include jQuery core. Use this to avoid loading it multiple times
2400 * before we get a usable script loader.
2402 * @param array $modules List of jQuery modules which should be loaded
2404 * Returns the list of modules which were not loaded.
2406 public function includeJQuery( $modules = array() ) {
2407 global $wgScriptPath, $wgStyleVersion, $wgJsMimeType;
2409 $supportedModules = array( /** TODO: add things here */ );
2410 $unsupported = array_diff( $modules, $supportedModules );
2413 'type' => $wgJsMimeType,
2414 'src' => "$wgScriptPath/skins/common/jquery.min.js?$wgStyleVersion",
2416 if ( !$this->mJQueryDone
) {
2417 $this->mJQueryDone
= true;
2418 $this->mScripts
= Html
::element( 'script', $params ) . "\n" . $this->mScripts
;
2420 return $unsupported;