ebdbcc687b3026999129d71ab2e227e26175f34c
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(), $mLanguageLinks = array();
17 var $mScriptLoaderClassList = array();
18 // the most recent id of any script that is grouped in the script request
19 var $mLatestScriptRevID = 0;
21 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
22 var $mTemplateIds = array();
25 var $mSuppressQuickbar = false;
26 var $mOnloadHandler = '';
27 var $mDoNothing = false;
28 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
29 var $mIsArticleRelated = true;
30 protected $mParserOptions = null; // lazy initialised, use parserOptions()
31 var $mShowFeedLinks = false;
32 var $mFeedLinksAppendQuery = false;
33 var $mEnableClientCache = true;
34 var $mArticleBodyOnly = false;
36 var $mNewSectionLink = false;
37 var $mHideNewSectionLink = false;
38 var $mNoGallery = false;
39 var $mPageTitleActionText = '';
40 var $mParseWarnings = array();
41 var $mSquidMaxage = 0;
42 var $mRevisionId = null;
43 protected $mTitle = null;
46 * An array of stylesheet filenames (relative from skins path), with options
47 * for CSS media, IE conditions, and RTL/LTR direction.
48 * For internal use; add settings in the skin via $this->addStyle()
50 var $styles = array();
52 private $mIndexPolicy = 'index';
53 private $mFollowPolicy = 'follow';
57 * Initialise private variables
59 function __construct() {
60 global $wgAllowUserJs;
61 $this->mAllowUserJs
= $wgAllowUserJs;
64 public function redirect( $url, $responsecode = '302' ) {
65 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
66 $this->mRedirect
= str_replace( "\n", '', $url );
67 $this->mRedirectCode
= $responsecode;
70 public function getRedirect() {
71 return $this->mRedirect
;
75 * Set the HTTP status code to send with the output.
77 * @param int $statusCode
80 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
83 * Add a new <meta> tag
84 * To add an http-equiv meta tag, precede the name with "http:"
86 * @param $name tag name
87 * @param $val tag value
89 function addMeta( $name, $val ) {
90 array_push( $this->mMetatags
, array( $name, $val ) );
93 function addKeyword( $text ) {
94 if( is_array( $text )) {
95 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
97 array_push( $this->mKeywords
, $text );
100 function addScript( $script ) {
101 $this->mScripts
.= $script . "\n";
105 * Register and add a stylesheet from an extension directory.
106 * @param $url String path to sheet. Provide either a full url (beginning
107 * with 'http', etc) or a relative path from the document root
108 * (beginning with '/'). Otherwise it behaves identically to
109 * addStyle() and draws from the /skins folder.
111 public function addExtensionStyle( $url ) {
112 array_push( $this->mExtStyles
, $url );
116 * Add a JavaScript file out of skins/common, or a given relative path.
117 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
119 function addScriptFile( $file ) {
120 global $wgStylePath, $wgScript, $wgUser;
121 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
123 if( substr( $file, 0, 1 ) == '/' ) {
126 $path = "{$wgStylePath}/common/{$file}";
129 if( $wgEnableScriptLoader ){
130 if( strpos( $path, $wgScript ) !== false ){
131 $reqPath = str_replace( $wgScript . '?', '', $path );
132 $reqArgs = explode( '&', $reqPath );
135 foreach( $reqArgs as $arg ){
136 list( $key, $var ) = explode( '=', $arg );
137 $reqSet[$key] = $var;
140 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
141 // extract any extra param (for now just skin)
142 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' ) ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
143 $this->mScriptLoaderClassList
[] = 'WT:' . $reqSet['title'] . $ext_param ;
144 // add the title revision to the key
145 $t = Title
::newFromText( $reqSet['title'] );
146 // if there is no title (don't worry we just use the $wgStyleVersion var (which should be updated on relevant commits)
147 if( $t && $t->exists() ){
148 if( $t->getLatestRevID() > $this->mLatestScriptRevID
)
149 $this->mLatestScriptRevID
= $t->getLatestRevID();
155 // check for class from path:
156 $js_class = $this->getJsClassFromPath( $path );
158 // add to the class list:
159 $this->mScriptLoaderClassList
[] = $js_class;
164 // if the script loader did not find a way to add the script than add using addScript
165 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
169 * This is the core script that is included on every page
170 * (they are requested separately to improve caching across
171 * different page load types (edit, upload, view, etc)
173 function addCoreScripts2Top(){
174 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgEnableJS2system;
175 //@@todo we should deprecate wikibits in favor of mv_embed and native jQuery functions
177 if( $wgEnableJS2system ){
178 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
180 $core_classes = array( 'wikibits' );
183 if( $wgEnableScriptLoader ){
184 $this->mScripts
= $this->getScriptLoaderJs( $core_classes ) . $this->mScripts
;
187 foreach( $core_classes as $s ){
188 if( isset( $wgJSAutoloadLocalClasses[$s] ) ){
189 $so .= Html
::linkedScript( "{$wgScriptPath}/{$wgJSAutoloadLocalClasses[$s]}?" . $this->getURIDparam() );
192 $this->mScripts
= $so . $this->mScripts
;
197 * @param $js_class String: name of JavaScript class
198 * @return Boolean: false if class wasn't found, true on success
200 function addScriptClass( $js_class ){
201 global $wgDebugJavaScript, $wgJSAutoloadLocalClasses, $wgJSAutoloadClasses,
202 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath;
204 if( isset( $wgJSAutoloadClasses[$js_class] ) ||
isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
205 if( $wgEnableScriptLoader ){
206 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ){
207 $this->mScriptLoaderClassList
[] = $js_class;
210 // do a normal load of without the script-loader:
211 $path = $wgScriptPath . '/';
212 if( isset( $wgJSAutoloadClasses[$js_class] ) ){
213 $path.= $wgJSAutoloadClasses[$js_class];
214 }else if( isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
215 $path.= $wgJSAutoloadLocalClasses[$js_class];
217 $urlAppend = ( $wgDebugJavaScript ) ?
time() : $wgStyleVersion;
218 $this->addScript( Html
::linkedScript( "$path?$urlAppend" ) );
222 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
223 return false; // could not find the class
227 * gets the scriptLoader javascript include
228 * @param $forcClassAry Boolean: false by default
230 function getScriptLoaderJs( $classAry = array() ){
231 global $wgRequest, $wgDebugJavaScript;
232 //if no class array provided use the mScriptLoaderClassList var
233 if( !count($classAry) ){
234 $classAry = $this->mScriptLoaderClassList
;
236 $class_list = implode(',', $classAry);
238 $debug_param = ( $wgDebugJavaScript ||
239 $wgRequest->getVal( 'debug' ) == 'true' ||
240 $wgRequest->getVal( 'debug' ) == '1' )
241 ?
'&debug=true' : '';
243 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) . "?class={$class_list}{$debug_param}&" . $this->getURIDparam( $classAry) );
246 function getURIDparam( $classAry=array() ){
247 global $wgDebugJavaScript, $wgStyleVersion, $IP, $wgScriptModifiedCheck;
248 if( $wgDebugJavaScript ){
249 return 'urid=' . time();
252 if($wgScriptModifiedCheck){
253 foreach( $classAry as $class ){
254 $js_path = jsScriptLoader
::getJsPathFromClass( $class );
256 $cur_ftime = filemtime ( $IP ."/". $js_path );
257 if( $cur_ftime > $ftime )
263 $urid = "urid={$wgStyleVersion}";
265 //if we have a $this->mLatestScriptRevID (wiki page revision ids)
266 if($this->mLatestScriptRevID
!= 0 )
267 $urid .= "_{$this->mLatestScriptRevID}";
276 function getJsClassFromPath( $path ){
277 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
279 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
280 foreach( $scriptLoaderPaths as $js_class => $js_path ){
281 $js_path = "{$wgScriptPath}/{$js_path}";
282 if( $path == $js_path )
289 * Add a self-contained script tag with the given contents
290 * @param string $script JavaScript text, no <script> tags
292 function addInlineScript( $script ) {
293 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
296 function getScript() {
297 global $wgEnableScriptLoader;
298 if( $wgEnableScriptLoader ){
299 //include $this->mScripts (for anything that we could not package into the scriptloader
300 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
302 return $this->mScripts
. $this->getHeadItems();
306 function getHeadItems() {
308 foreach ( $this->mHeadItems
as $item ) {
314 function addHeadItem( $name, $value ) {
315 $this->mHeadItems
[$name] = $value;
318 function hasHeadItem( $name ) {
319 return isset( $this->mHeadItems
[$name] );
322 function setETag($tag) { $this->mETag
= $tag; }
323 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
324 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
326 function addLink( $linkarr ) {
327 # $linkarr should be an associative array of attributes. We'll escape on output.
328 array_push( $this->mLinktags
, $linkarr );
331 # Get all links added by extensions
332 function getExtStyle() {
333 return $this->mExtStyles
;
336 function addMetadataLink( $linkarr ) {
337 # note: buggy CC software only reads first "meta" link
338 static $haveMeta = false;
339 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
340 $this->addLink( $linkarr );
345 * checkLastModified tells the client to use the client-cached page if
346 * possible. If sucessful, the OutputPage is disabled so that
347 * any future call to OutputPage->output() have no effect.
349 * Side effect: sets mLastModified for Last-Modified header
351 * @return bool True iff cache-ok headers was sent.
353 function checkLastModified( $timestamp ) {
354 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
356 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
357 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
360 if( !$wgCachePages ) {
361 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
364 if( $wgUser->getOption( 'nocache' ) ) {
365 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
369 $timestamp = wfTimestamp( TS_MW
, $timestamp );
370 $modifiedTimes = array(
371 'page' => $timestamp,
372 'user' => $wgUser->getTouched(),
373 'epoch' => $wgCacheEpoch
375 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
377 $maxModified = max( $modifiedTimes );
378 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
380 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
381 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
387 foreach ( $modifiedTimes as $name => $value ) {
388 if ( $info !== '' ) {
391 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
394 # IE sends sizes after the date like this:
395 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
396 # this breaks strtotime().
397 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
399 wfSuppressWarnings(); // E_STRICT system time bitching
400 $clientHeaderTime = strtotime( $clientHeader );
402 if ( !$clientHeaderTime ) {
403 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
406 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
408 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
409 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
410 wfDebug( __METHOD__
. ": effective Last-Modified: " .
411 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
412 if( $clientHeaderTime < $maxModified ) {
413 wfDebug( __METHOD__
. ": STALE, $info\n", false );
418 # Give a 304 response code and disable body output
419 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
420 ini_set('zlib.output_compression', 0);
421 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
422 $this->sendCacheControl();
425 // Don't output a compressed blob when using ob_gzhandler;
426 // it's technically against HTTP spec and seems to confuse
427 // Firefox when the response gets split over two packets.
428 wfClearOutputBuffers();
433 function setPageTitleActionText( $text ) {
434 $this->mPageTitleActionText
= $text;
437 function getPageTitleActionText () {
438 if ( isset( $this->mPageTitleActionText
) ) {
439 return $this->mPageTitleActionText
;
444 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
446 * @param $policy string The literal string to output as the contents of
447 * the meta tag. Will be parsed according to the spec and output in
451 public function setRobotPolicy( $policy ) {
452 $policy = Article
::formatRobotPolicy( $policy );
454 if( isset( $policy['index'] ) ){
455 $this->setIndexPolicy( $policy['index'] );
457 if( isset( $policy['follow'] ) ){
458 $this->setFollowPolicy( $policy['follow'] );
463 * Set the index policy for the page, but leave the follow policy un-
466 * @param $policy string Either 'index' or 'noindex'.
469 public function setIndexPolicy( $policy ) {
470 $policy = trim( $policy );
471 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
472 $this->mIndexPolicy
= $policy;
477 * Set the follow policy for the page, but leave the index policy un-
480 * @param $policy string Either 'follow' or 'nofollow'.
483 public function setFollowPolicy( $policy ) {
484 $policy = trim( $policy );
485 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
486 $this->mFollowPolicy
= $policy;
491 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
493 public function setHTMLTitle( $name ) {
494 $this->mHTMLtitle
= $name;
498 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
499 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
500 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
501 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
503 public function setPageTitle( $name ) {
505 $name = $wgContLang->convert( $name, true );
506 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
507 # but leave "<i>foobar</i>" alone
508 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
509 $this->mPagetitle
= $nameWithTags;
511 $taction = $this->getPageTitleActionText();
512 if( !empty( $taction ) ) {
513 $name .= ' - '.$taction;
516 # change "<i>foo&bar</i>" to "foo&bar"
517 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
520 public function setTitle( $t ) {
524 public function getTitle() {
525 if ( $this->mTitle
instanceof Title
) {
526 return $this->mTitle
;
529 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
535 public function getHTMLTitle() { return $this->mHTMLtitle
; }
536 public function getPageTitle() { return $this->mPagetitle
; }
537 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
538 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
539 public function getSubtitle() { return $this->mSubtitle
; }
540 public function isArticle() { return $this->mIsarticle
; }
541 public function setPrintable() { $this->mPrintable
= true; }
542 public function isPrintable() { return $this->mPrintable
; }
543 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
544 public function isSyndicated() { return $this->mShowFeedLinks
; }
545 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
546 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
547 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
548 public function getOnloadHandler() { return $this->mOnloadHandler
; }
549 public function disable() { $this->mDoNothing
= true; }
550 public function isDisabled() { return $this->mDoNothing
; }
552 public function setArticleRelated( $v ) {
553 $this->mIsArticleRelated
= $v;
555 $this->mIsarticle
= false;
558 public function setArticleFlag( $v ) {
559 $this->mIsarticle
= $v;
561 $this->mIsArticleRelated
= $v;
565 public function isArticleRelated() { return $this->mIsArticleRelated
; }
567 public function getLanguageLinks() { return $this->mLanguageLinks
; }
568 public function addLanguageLinks($newLinkArray) {
569 $this->mLanguageLinks +
= $newLinkArray;
571 public function setLanguageLinks($newLinkArray) {
572 $this->mLanguageLinks
= $newLinkArray;
575 public function getCategoryLinks() {
576 return $this->mCategoryLinks
;
580 * Add an array of categories, with names in the keys
582 public function addCategoryLinks( $categories ) {
583 global $wgUser, $wgContLang;
585 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
589 # Add the links to a LinkBatch
590 $arr = array( NS_CATEGORY
=> $categories );
592 $lb->setArray( $arr );
594 # Fetch existence plus the hiddencat property
595 $dbr = wfGetDB( DB_SLAVE
);
596 $pageTable = $dbr->tableName( 'page' );
597 $where = $lb->constructSet( 'page', $dbr );
598 $propsTable = $dbr->tableName( 'page_props' );
599 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
600 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
601 $res = $dbr->query( $sql, __METHOD__
);
603 # Add the results to the link cache
604 $lb->addResultToCache( LinkCache
::singleton(), $res );
606 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
607 $categories = array_combine( array_keys( $categories ),
608 array_fill( 0, count( $categories ), 'normal' ) );
610 # Mark hidden categories
611 foreach ( $res as $row ) {
612 if ( isset( $row->pp_value
) ) {
613 $categories[$row->page_title
] = 'hidden';
617 # Add the remaining categories to the skin
618 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
619 $sk = $wgUser->getSkin();
620 foreach ( $categories as $category => $type ) {
621 $origcategory = $category;
622 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
623 $wgContLang->findVariantLink( $category, $title, true );
624 if ( $category != $origcategory )
625 if ( array_key_exists( $category, $categories ) )
627 $text = $wgContLang->convertHtml( $title->getText() );
628 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
633 public function setCategoryLinks($categories) {
634 $this->mCategoryLinks
= array();
635 $this->addCategoryLinks($categories);
638 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
639 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
641 public function disallowUserJs() { $this->mAllowUserJs
= false; }
642 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
644 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
645 public function addHTML( $text ) { $this->mBodytext
.= $text; }
646 public function clearHTML() { $this->mBodytext
= ''; }
647 public function getHTML() { return $this->mBodytext
; }
648 public function debug( $text ) { $this->mDebugtext
.= $text; }
651 public function setParserOptions( $options ) {
652 wfDeprecated( __METHOD__
);
653 return $this->parserOptions( $options );
656 public function parserOptions( $options = null ) {
657 if ( !$this->mParserOptions
) {
658 $this->mParserOptions
= new ParserOptions
;
660 return wfSetVar( $this->mParserOptions
, $options );
664 * Set the revision ID which will be seen by the wiki text parser
665 * for things such as embedded {{REVISIONID}} variable use.
666 * @param mixed $revid an integer, or NULL
667 * @return mixed previous value
669 public function setRevisionId( $revid ) {
670 $val = is_null( $revid ) ?
null : intval( $revid );
671 return wfSetVar( $this->mRevisionId
, $val );
674 public function getRevisionId() {
675 return $this->mRevisionId
;
679 * Convert wikitext to HTML and add it to the buffer
680 * Default assumes that the current page title will
683 * @param string $text
684 * @param bool $linestart
686 public function addWikiText( $text, $linestart = true ) {
687 $title = $this->getTitle(); // Work arround E_STRICT
688 $this->addWikiTextTitle( $text, $title, $linestart );
691 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
692 $this->addWikiTextTitle($text, $title, $linestart);
695 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
696 $this->addWikiTextTitle( $text, $title, $linestart, true );
699 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
702 wfProfileIn( __METHOD__
);
704 wfIncrStats( 'pcache_not_possible' );
706 $popts = $this->parserOptions();
707 $oldTidy = $popts->setTidy( $tidy );
709 $parserOutput = $wgParser->parse( $text, $title, $popts,
710 $linestart, true, $this->mRevisionId
);
712 $popts->setTidy( $oldTidy );
714 $this->addParserOutput( $parserOutput );
716 wfProfileOut( __METHOD__
);
721 * @param ParserOutput object &$parserOutput
723 public function addParserOutputNoText( &$parserOutput ) {
724 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
726 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
727 $this->addCategoryLinks( $parserOutput->getCategories() );
728 $this->mNewSectionLink
= $parserOutput->getNewSection();
729 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
731 $this->mParseWarnings
= $parserOutput->getWarnings();
732 if ( $parserOutput->getCacheTime() == -1 ) {
733 $this->enableClientCache( false );
735 $this->mNoGallery
= $parserOutput->getNoGallery();
736 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
738 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
739 if ( isset( $this->mTemplateIds
[$ns] ) ) {
740 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
742 $this->mTemplateIds
[$ns] = $dbks;
746 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
747 $this->setPageTitle( $dt );
748 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
749 $this->setPageTitle( $title );
751 // Hooks registered in the object
752 global $wgParserOutputHooks;
753 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
754 list( $hookName, $data ) = $hookInfo;
755 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
756 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
760 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
765 * @param ParserOutput &$parserOutput
767 function addParserOutput( &$parserOutput ) {
768 $this->addParserOutputNoText( $parserOutput );
769 $text = $parserOutput->getText();
770 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
771 $this->addHTML( $text );
775 * Add wikitext to the buffer, assuming that this is the primary text for a page view
776 * Saves the text into the parser cache if possible.
778 * @param string $text
779 * @param Article $article
781 * @deprecated Use Article::outputWikitext
783 public function addPrimaryWikiText( $text, $article, $cache = true ) {
786 wfDeprecated( __METHOD__
);
788 $popts = $this->parserOptions();
789 $popts->setTidy(true);
790 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
791 $popts, true, true, $this->mRevisionId
);
792 $popts->setTidy(false);
793 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
794 $parserCache = ParserCache
::singleton();
795 $parserCache->save( $parserOutput, $article, $popts);
798 $this->addParserOutput( $parserOutput );
802 * @deprecated use addWikiTextTidy()
804 public function addSecondaryWikiText( $text, $linestart = true ) {
805 wfDeprecated( __METHOD__
);
806 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
810 * Add wikitext with tidy enabled
812 public function addWikiTextTidy( $text, $linestart = true ) {
813 $title = $this->getTitle();
814 $this->addWikiTextTitleTidy($text, $title, $linestart);
819 * Add the output of a QuickTemplate to the output buffer
821 * @param QuickTemplate $template
823 public function addTemplate( &$template ) {
825 $template->execute();
826 $this->addHTML( ob_get_contents() );
831 * Parse wikitext and return the HTML.
833 * @param string $text
834 * @param bool $linestart Is this the start of a line?
835 * @param bool $interface ??
837 public function parse( $text, $linestart = true, $interface = false ) {
839 if( is_null( $this->getTitle() ) ) {
840 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
842 $popts = $this->parserOptions();
843 if ( $interface) { $popts->setInterfaceMessage(true); }
844 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
845 $linestart, true, $this->mRevisionId
);
846 if ( $interface) { $popts->setInterfaceMessage(false); }
847 return $parserOutput->getText();
850 /** Parse wikitext, strip paragraphs, and return the HTML. */
851 public function parseInline( $text, $linestart = true, $interface = false ) {
852 $parsed = $this->parse( $text, $linestart, $interface );
855 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
863 * @param Article $article
868 * @return bool True if successful, else false.
870 public function tryParserCache( &$article ) {
871 wfDeprecated( __METHOD__
);
872 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
874 if ($parserOutput !== false) {
875 $this->addParserOutput( $parserOutput );
883 * @param int $maxage Maximum cache time on the Squid, in seconds.
885 public function setSquidMaxage( $maxage ) {
886 $this->mSquidMaxage
= $maxage;
890 * Use enableClientCache(false) to force it to send nocache headers
893 public function enableClientCache( $state ) {
894 return wfSetVar( $this->mEnableClientCache
, $state );
897 function getCacheVaryCookies() {
898 global $wgCookiePrefix, $wgCacheVaryCookies;
900 if ( $cookies === null ) {
901 $cookies = array_merge(
903 "{$wgCookiePrefix}Token",
904 "{$wgCookiePrefix}LoggedOut",
909 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
914 function uncacheableBecauseRequestVars() {
916 return $wgRequest->getText('useskin', false) === false
917 && $wgRequest->getText('uselang', false) === false;
921 * Check if the request has a cache-varying cookie header
922 * If it does, it's very important that we don't allow public caching
924 function haveCacheVaryCookies() {
926 $cookieHeader = $wgRequest->getHeader( 'cookie' );
927 if ( $cookieHeader === false ) {
930 $cvCookies = $this->getCacheVaryCookies();
931 foreach ( $cvCookies as $cookieName ) {
932 # Check for a simple string match, like the way squid does it
933 if ( strpos( $cookieHeader, $cookieName ) ) {
934 wfDebug( __METHOD__
.": found $cookieName\n" );
938 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
942 /** Get a complete X-Vary-Options header */
943 public function getXVO() {
944 $cvCookies = $this->getCacheVaryCookies();
945 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
947 foreach ( $cvCookies as $cookieName ) {
953 $xvo .= 'string-contains=' . $cookieName;
958 public function sendCacheControl() {
959 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
961 $response = $wgRequest->response();
962 if ($wgUseETag && $this->mETag
)
963 $response->header("ETag: $this->mETag");
965 # don't serve compressed data to clients who can't handle it
966 # maintain different caches for logged-in users and non-logged in ones
967 $response->header( 'Vary: Accept-Encoding, Cookie' );
970 # Add an X-Vary-Options header for Squid with Wikimedia patches
971 $response->header( $this->getXVO() );
974 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
975 if( $wgUseSquid && session_id() == '' &&
976 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
979 # We'll purge the proxy cache explicitly, but require end user agents
980 # to revalidate against the proxy on each visit.
981 # Surrogate-Control controls our Squid, Cache-Control downstream caches
982 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
983 # start with a shorter timeout for initial testing
984 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
985 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
986 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
988 # We'll purge the proxy cache for anons explicitly, but require end user agents
989 # to revalidate against the proxy on each visit.
990 # IMPORTANT! The Squid needs to replace the Cache-Control header with
991 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
992 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
993 # start with a shorter timeout for initial testing
994 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
995 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
998 # We do want clients to cache if they can, but they *must* check for updates
999 # on revisiting the page.
1000 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1001 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1002 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1004 if($this->mLastModified
) {
1005 $response->header( "Last-Modified: {$this->mLastModified}" );
1008 wfDebug( __METHOD__
. ": no caching **\n", false );
1010 # In general, the absence of a last modified header should be enough to prevent
1011 # the client from using its cache. We send a few other things just to make sure.
1012 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1013 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1014 $response->header( 'Pragma: no-cache' );
1019 * Finally, all the text has been munged and accumulated into
1020 * the object, let's actually output it:
1022 public function output() {
1023 global $wgUser, $wgOutputEncoding, $wgRequest;
1024 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1025 global $wgUseAjax, $wgAjaxWatch;
1026 global $wgEnableMWSuggest, $wgUniversalEditButton;
1029 if( $this->mDoNothing
){
1032 wfProfileIn( __METHOD__
);
1033 if ( '' != $this->mRedirect
) {
1034 # Standards require redirect URLs to be absolute
1035 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1036 if( $this->mRedirectCode
== '301') {
1037 if( !$wgDebugRedirects ) {
1038 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1040 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1042 $this->sendCacheControl();
1044 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1045 if( $wgDebugRedirects ) {
1046 $url = htmlspecialchars( $this->mRedirect
);
1047 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1048 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1049 print "</body>\n</html>\n";
1051 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1053 wfProfileOut( __METHOD__
);
1056 elseif ( $this->mStatusCode
)
1058 $statusMessage = array(
1060 101 => 'Switching Protocols',
1061 102 => 'Processing',
1065 203 => 'Non-Authoritative Information',
1066 204 => 'No Content',
1067 205 => 'Reset Content',
1068 206 => 'Partial Content',
1069 207 => 'Multi-Status',
1070 300 => 'Multiple Choices',
1071 301 => 'Moved Permanently',
1074 304 => 'Not Modified',
1076 307 => 'Temporary Redirect',
1077 400 => 'Bad Request',
1078 401 => 'Unauthorized',
1079 402 => 'Payment Required',
1082 405 => 'Method Not Allowed',
1083 406 => 'Not Acceptable',
1084 407 => 'Proxy Authentication Required',
1085 408 => 'Request Timeout',
1088 411 => 'Length Required',
1089 412 => 'Precondition Failed',
1090 413 => 'Request Entity Too Large',
1091 414 => 'Request-URI Too Large',
1092 415 => 'Unsupported Media Type',
1093 416 => 'Request Range Not Satisfiable',
1094 417 => 'Expectation Failed',
1095 422 => 'Unprocessable Entity',
1097 424 => 'Failed Dependency',
1098 500 => 'Internal Server Error',
1099 501 => 'Not Implemented',
1100 502 => 'Bad Gateway',
1101 503 => 'Service Unavailable',
1102 504 => 'Gateway Timeout',
1103 505 => 'HTTP Version Not Supported',
1104 507 => 'Insufficient Storage'
1107 if ( $statusMessage[$this->mStatusCode
] )
1108 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1111 $sk = $wgUser->getSkin();
1113 // add our core scripts to output
1114 $this->addCoreScripts2Top();
1117 $this->addScriptFile( 'ajax.js' );
1119 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1121 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1122 $this->addScriptFile( 'ajaxwatch.js' );
1125 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1126 $this->addScriptFile( 'mwsuggest.js' );
1130 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1131 $this->addScriptFile( 'rightclickedit.js' );
1134 global $wgUseAJAXCategories;
1135 if ($wgUseAJAXCategories) {
1136 $this->addScriptClass( 'ajaxCategories' );
1139 if( $wgUniversalEditButton ) {
1140 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1141 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1142 // Original UniversalEditButton
1143 $msg = wfMsg('edit');
1144 $this->addLink( array(
1145 'rel' => 'alternate',
1146 'type' => 'application/x-wiki',
1148 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1150 // Alternate edit link
1151 $this->addLink( array(
1154 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1159 # Buffer output; final headers may depend on later processing
1162 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1163 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1165 if ($this->mArticleBodyOnly
) {
1166 $this->out($this->mBodytext
);
1168 // Hook that allows last minute changes to the output page, e.g.
1169 // adding of CSS or Javascript by extensions.
1170 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1172 wfProfileIn( 'Output-skin' );
1173 $sk->outputPage( $this );
1174 wfProfileOut( 'Output-skin' );
1177 $this->sendCacheControl();
1179 wfProfileOut( __METHOD__
);
1183 * Actually output something with print(). Performs an iconv to the
1184 * output encoding, if needed.
1185 * @param string $ins The string to output
1187 public function out( $ins ) {
1188 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1189 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1192 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1193 if ( false === $outs ) { $outs = $ins; }
1201 public static function setEncodings() {
1202 global $wgInputEncoding, $wgOutputEncoding;
1205 $wgInputEncoding = strtolower( $wgInputEncoding );
1207 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1208 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1211 $wgOutputEncoding = $wgInputEncoding;
1215 * Deprecated, use wfReportTime() instead.
1219 public function reportTime() {
1220 wfDeprecated( __METHOD__
);
1221 $time = wfReportTime();
1226 * Produce a "user is blocked" page.
1228 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1231 function blockedPage( $return = true ) {
1232 global $wgUser, $wgContLang, $wgLang;
1234 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1235 $this->setRobotPolicy( 'noindex,nofollow' );
1236 $this->setArticleRelated( false );
1238 $name = User
::whoIs( $wgUser->blockedBy() );
1239 $reason = $wgUser->blockedFor();
1240 if( $reason == '' ) {
1241 $reason = wfMsg( 'blockednoreason' );
1243 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1246 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1248 $blockid = $wgUser->mBlock
->mId
;
1250 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1251 if ( $blockExpiry == 'infinity' ) {
1252 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1253 // Search for localization in 'ipboptions'
1254 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1255 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1256 if ( strpos( $option, ":" ) === false )
1258 list( $show, $value ) = explode( ":", $option );
1259 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1260 $blockExpiry = $show;
1265 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1268 if ( $wgUser->mBlock
->mAuto
) {
1269 $msg = 'autoblockedtext';
1271 $msg = 'blockedtext';
1274 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1275 * This could be a username, an ip range, or a single ip. */
1276 $intended = $wgUser->mBlock
->mAddress
;
1278 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1280 # Don't auto-return to special pages
1282 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1283 $this->returnToMain( null, $return );
1288 * Output a standard error page
1290 * @param string $title Message key for page title
1291 * @param string $msg Message key for page text
1292 * @param array $params Message parameters
1294 public function showErrorPage( $title, $msg, $params = array() ) {
1295 if ( $this->getTitle() ) {
1296 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1298 $this->setPageTitle( wfMsg( $title ) );
1299 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1300 $this->setRobotPolicy( 'noindex,nofollow' );
1301 $this->setArticleRelated( false );
1302 $this->enableClientCache( false );
1303 $this->mRedirect
= '';
1304 $this->mBodytext
= '';
1306 array_unshift( $params, 'parse' );
1307 array_unshift( $params, $msg );
1308 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1310 $this->returnToMain();
1314 * Output a standard permission error page
1316 * @param array $errors Error message keys
1318 public function showPermissionsErrorPage( $errors, $action = null )
1320 $this->mDebugtext
.= 'Original title: ' .
1321 $this->getTitle()->getPrefixedText() . "\n";
1322 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1323 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1324 $this->setRobotPolicy( 'noindex,nofollow' );
1325 $this->setArticleRelated( false );
1326 $this->enableClientCache( false );
1327 $this->mRedirect
= '';
1328 $this->mBodytext
= '';
1329 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1333 public function errorpage( $title, $msg ) {
1334 wfDeprecated( __METHOD__
);
1335 throw new ErrorPageError( $title, $msg );
1339 * Display an error page indicating that a given version of MediaWiki is
1340 * required to use it
1342 * @param mixed $version The version of MediaWiki needed to use the page
1344 public function versionRequired( $version ) {
1345 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1346 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1347 $this->setRobotPolicy( 'noindex,nofollow' );
1348 $this->setArticleRelated( false );
1349 $this->mBodytext
= '';
1351 $this->addWikiMsg( 'versionrequiredtext', $version );
1352 $this->returnToMain();
1356 * Display an error page noting that a given permission bit is required.
1358 * @param string $permission key required
1360 public function permissionRequired( $permission ) {
1363 $this->setPageTitle( wfMsg( 'badaccess' ) );
1364 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1365 $this->setRobotPolicy( 'noindex,nofollow' );
1366 $this->setArticleRelated( false );
1367 $this->mBodytext
= '';
1369 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1370 User
::getGroupsWithPermission( $permission ) );
1372 $this->addWikiMsg( 'badaccess-groups',
1373 $wgLang->commaList( $groups ),
1376 $this->addWikiMsg( 'badaccess-group0' );
1378 $this->returnToMain();
1382 * Use permissionRequired.
1385 public function sysopRequired() {
1386 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1390 * Use permissionRequired.
1393 public function developerRequired() {
1394 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1398 * Produce the stock "please login to use the wiki" page
1400 public function loginToUse() {
1401 global $wgUser, $wgContLang;
1403 if( $wgUser->isLoggedIn() ) {
1404 $this->permissionRequired( 'read' );
1408 $skin = $wgUser->getSkin();
1410 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1411 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1412 $this->setRobotPolicy( 'noindex,nofollow' );
1413 $this->setArticleFlag( false );
1415 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1416 $loginLink = $skin->link(
1418 wfMsgHtml( 'loginreqlink' ),
1420 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1421 array( 'known', 'noclasses' )
1423 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1424 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1426 # Don't return to the main page if the user can't read it
1427 # otherwise we'll end up in a pointless loop
1428 $mainPage = Title
::newMainPage();
1429 if( $mainPage->userCanRead() )
1430 $this->returnToMain( null, $mainPage );
1434 public function databaseError( $fname, $sql, $error, $errno ) {
1435 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1439 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1440 * @return string The wikitext error-messages, formatted into a list.
1442 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1443 if ($action == null) {
1444 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1447 $action_desc = wfMsgNoTrans( "action-$action" );
1448 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1451 if (count( $errors ) > 1) {
1452 $text .= '<ul class="permissions-errors">' . "\n";
1454 foreach( $errors as $error )
1457 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1462 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1469 * Display a page stating that the Wiki is in read-only mode,
1470 * and optionally show the source of the page that the user
1471 * was trying to edit. Should only be called (for this
1472 * purpose) after wfReadOnly() has returned true.
1474 * For historical reasons, this function is _also_ used to
1475 * show the error message when a user tries to edit a page
1476 * they are not allowed to edit. (Unless it's because they're
1477 * blocked, then we show blockedPage() instead.) In this
1478 * case, the second parameter should be set to true and a list
1479 * of reasons supplied as the third parameter.
1481 * @todo Needs to be split into multiple functions.
1483 * @param string $source Source code to show (or null).
1484 * @param bool $protected Is this a permissions error?
1485 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1487 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1489 $skin = $wgUser->getSkin();
1491 $this->setRobotPolicy( 'noindex,nofollow' );
1492 $this->setArticleRelated( false );
1494 // If no reason is given, just supply a default "I can't let you do
1495 // that, Dave" message. Should only occur if called by legacy code.
1496 if ( $protected && empty($reasons) ) {
1497 $reasons[] = array( 'badaccess-group0' );
1500 if ( !empty($reasons) ) {
1501 // Permissions error
1503 $this->setPageTitle( wfMsg( 'viewsource' ) );
1512 array( 'known', 'noclasses' )
1517 $this->setPageTitle( wfMsg( 'badaccess' ) );
1519 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1521 // Wiki is read only
1522 $this->setPageTitle( wfMsg( 'readonly' ) );
1523 $reason = wfReadOnlyReason();
1524 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1527 // Show source, if supplied
1528 if( is_string( $source ) ) {
1529 $this->addWikiMsg( 'viewsourcetext' );
1530 $text = Xml
::openElement( 'textarea',
1531 array( 'id' => 'wpTextbox1',
1532 'name' => 'wpTextbox1',
1533 'cols' => $wgUser->getOption( 'cols' ),
1534 'rows' => $wgUser->getOption( 'rows' ),
1535 'readonly' => 'readonly' ) );
1536 $text .= htmlspecialchars( $source );
1537 $text .= Xml
::closeElement( 'textarea' );
1538 $this->addHTML( $text );
1540 // Show templates used by this article
1541 $skin = $wgUser->getSkin();
1542 $article = new Article( $this->getTitle() );
1543 $this->addHTML( "<div class='templatesUsed'>
1544 {$skin->formatTemplates( $article->getUsedTemplates() )}
1549 # If the title doesn't exist, it's fairly pointless to print a return
1550 # link to it. After all, you just tried editing it and couldn't, so
1551 # what's there to do there?
1552 if( $this->getTitle()->exists() ) {
1553 $this->returnToMain( null, $this->getTitle() );
1558 public function fatalError( $message ) {
1559 wfDeprecated( __METHOD__
);
1560 throw new FatalError( $message );
1564 public function unexpectedValueError( $name, $val ) {
1565 wfDeprecated( __METHOD__
);
1566 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1570 public function fileCopyError( $old, $new ) {
1571 wfDeprecated( __METHOD__
);
1572 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1576 public function fileRenameError( $old, $new ) {
1577 wfDeprecated( __METHOD__
);
1578 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1582 public function fileDeleteError( $name ) {
1583 wfDeprecated( __METHOD__
);
1584 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1588 public function fileNotFoundError( $name ) {
1589 wfDeprecated( __METHOD__
);
1590 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1593 public function showFatalError( $message ) {
1594 $this->setPageTitle( wfMsg( "internalerror" ) );
1595 $this->setRobotPolicy( "noindex,nofollow" );
1596 $this->setArticleRelated( false );
1597 $this->enableClientCache( false );
1598 $this->mRedirect
= '';
1599 $this->mBodytext
= $message;
1602 public function showUnexpectedValueError( $name, $val ) {
1603 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1606 public function showFileCopyError( $old, $new ) {
1607 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1610 public function showFileRenameError( $old, $new ) {
1611 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1614 public function showFileDeleteError( $name ) {
1615 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1618 public function showFileNotFoundError( $name ) {
1619 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1623 * Add a "return to" link pointing to a specified title
1625 * @param Title $title Title to link
1626 * @param string $query Query string
1628 public function addReturnTo( $title, $query = array() ) {
1630 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1631 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1632 $title, null, array(), $query ) );
1633 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1637 * Add a "return to" link pointing to a specified title,
1638 * or the title indicated in the request, or else the main page
1640 * @param null $unused No longer used
1641 * @param Title $returnto Title to return to
1643 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1646 if ( $returnto == null ) {
1647 $returnto = $wgRequest->getText( 'returnto' );
1650 if ( $returntoquery == null ) {
1651 $returntoquery = $wgRequest->getText( 'returntoquery' );
1654 if ( '' === $returnto ) {
1655 $returnto = Title
::newMainPage();
1658 if ( is_object( $returnto ) ) {
1659 $titleObj = $returnto;
1661 $titleObj = Title
::newFromText( $returnto );
1663 if ( !is_object( $titleObj ) ) {
1664 $titleObj = Title
::newMainPage();
1667 $this->addReturnTo( $titleObj, $returntoquery );
1671 * @return string The doctype, opening <html>, and head element.
1673 public function headElement( Skin
$sk ) {
1674 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1675 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1676 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1678 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1679 if ( $sk->commonPrintStylesheet() ) {
1680 $this->addStyle( 'common/wikiprintable.css', 'print' );
1682 $sk->setupUserCss( $this );
1686 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1687 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1690 if ( '' == $this->getHTMLTitle() ) {
1691 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1694 $dir = $wgContLang->getDir();
1697 $ret .= "<!doctype html>\n";
1698 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1700 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1701 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1702 foreach($wgXhtmlNamespaces as $tag => $ns) {
1703 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1705 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1709 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1710 $ret .= implode( "\n", array(
1711 $this->getHeadLinks(),
1712 $this->buildCssLinks(),
1713 $sk->getHeadScripts( $this ),
1714 $this->getHeadItems(),
1717 $ret .= Html
::inlineStyle( $sk->usercss
);
1720 if( $wgEnableScriptLoader )
1721 $ret .= $this->getScriptLoaderJs();
1723 if ($wgUseTrackbacks && $this->isArticleRelated())
1724 $ret .= $this->getTitle()->trackbackRDF();
1726 $ret .= "</head>\n";
1730 protected function addDefaultMeta() {
1731 global $wgVersion, $wgHtml5;
1733 static $called = false;
1735 # Don't run this twice
1741 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1743 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1745 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1746 if( $p !== 'index,follow' ) {
1747 // http://www.robotstxt.org/wc/meta-user.html
1748 // Only show if it's different from the default robots policy
1749 $this->addMeta( 'robots', $p );
1752 if ( count( $this->mKeywords
) > 0 ) {
1754 "/<.*?" . ">/" => '',
1757 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1762 * @return string HTML tag links to be put in the header.
1764 public function getHeadLinks() {
1765 global $wgRequest, $wgFeed;
1767 // Ideally this should happen earlier, somewhere. :P
1768 $this->addDefaultMeta();
1772 foreach ( $this->mMetatags
as $tag ) {
1773 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1775 $tag[0] = substr( $tag[0], 5 );
1779 $tags[] = Xml
::element( 'meta',
1782 'content' => $tag[1] ) );
1784 foreach ( $this->mLinktags
as $tag ) {
1785 $tags[] = Xml
::element( 'link', $tag );
1789 foreach( $this->getSyndicationLinks() as $format => $link ) {
1790 # Use the page name for the title (accessed through $wgTitle since
1791 # there's no other way). In principle, this could lead to issues
1792 # with having the same name for different feeds corresponding to
1793 # the same page, but we can't avoid that at this low a level.
1795 $tags[] = $this->feedLink(
1798 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1801 # Recent changes feed should appear on every page (except recentchanges,
1802 # that would be redundant). Put it after the per-page feed to avoid
1803 # changing existing behavior. It's still available, probably via a
1804 # menu in your browser. Some sites might have a different feed they'd
1805 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1806 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1807 # If so, use it instead.
1809 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1810 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1812 if ( $wgOverrideSiteFeed ) {
1813 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1814 $tags[] = $this->feedLink (
1816 htmlspecialchars( $feedUrl ),
1817 wfMsg( "site-{$type}-feed", $wgSitename ) );
1820 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1821 foreach( $wgFeedClasses as $format => $class ) {
1822 $tags[] = $this->feedLink(
1824 $rctitle->getLocalURL( "feed={$format}" ),
1825 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1830 return implode( "\n", $tags ) . "\n";
1834 * Return URLs for each supported syndication format for this page.
1835 * @return array associating format keys with URLs
1837 public function getSyndicationLinks() {
1838 global $wgFeedClasses;
1841 if( $this->isSyndicated() ) {
1842 if( is_string( $this->getFeedAppendQuery() ) ) {
1843 $appendQuery = "&" . $this->getFeedAppendQuery();
1848 foreach( $wgFeedClasses as $format => $class ) {
1849 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1856 * Generate a <link rel/> for an RSS feed.
1858 private function feedLink( $type, $url, $text ) {
1859 return Xml
::element( 'link', array(
1860 'rel' => 'alternate',
1861 'type' => "application/$type+xml",
1867 * Add a local or specified stylesheet, with the given media options.
1868 * Meant primarily for internal use...
1870 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1871 * @param $conditional -- for IE conditional comments, specifying an IE version
1872 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1874 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1876 // Even though we expect the media type to be lowercase, but here we
1877 // force it to lowercase to be safe.
1879 $options['media'] = $media;
1881 $options['condition'] = $condition;
1883 $options['dir'] = $dir;
1884 $this->styles
[$style] = $options;
1888 * Adds inline CSS styles
1889 * @param $style_css Mixed: inline CSS
1891 public function addInlineStyle( $style_css ){
1892 $this->mScripts
.= Html
::inlineStyle( $style_css );
1896 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1897 * These will be applied to various media & IE conditionals.
1899 public function buildCssLinks() {
1901 foreach( $this->styles
as $file => $options ) {
1902 $link = $this->styleLink( $file, $options );
1907 return implode( "\n", $links );
1910 protected function styleLink( $style, $options ) {
1913 if( isset( $options['dir'] ) ) {
1915 $siteDir = $wgContLang->getDir();
1916 if( $siteDir != $options['dir'] )
1920 if( isset( $options['media'] ) ) {
1921 $media = $this->transformCssMedia( $options['media'] );
1922 if( is_null( $media ) ) {
1929 if( substr( $style, 0, 1 ) == '/' ||
1930 substr( $style, 0, 5 ) == 'http:' ||
1931 substr( $style, 0, 6 ) == 'https:' ) {
1934 global $wgStylePath, $wgStyleVersion;
1935 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1938 $link = Html
::linkedStyle( $url, $media );
1940 if( isset( $options['condition'] ) ) {
1941 $condition = htmlspecialchars( $options['condition'] );
1942 $link = "<!--[if $condition]>$link<![endif]-->";
1947 function transformCssMedia( $media ) {
1948 global $wgRequest, $wgHandheldForIPhone;
1950 // Switch in on-screen display for media testing
1952 'printable' => 'print',
1953 'handheld' => 'handheld',
1955 foreach( $switches as $switch => $targetMedia ) {
1956 if( $wgRequest->getBool( $switch ) ) {
1957 if( $media == $targetMedia ) {
1959 } elseif( $media == 'screen' ) {
1965 // Expand longer media queries as iPhone doesn't grok 'handheld'
1966 if( $wgHandheldForIPhone ) {
1967 $mediaAliases = array(
1968 'screen' => 'screen and (min-device-width: 481px)',
1969 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1972 if( isset( $mediaAliases[$media] ) ) {
1973 $media = $mediaAliases[$media];
1981 * Turn off regular page output and return an error reponse
1982 * for when rate limiting has triggered.
1984 public function rateLimited() {
1986 $this->setPageTitle(wfMsg('actionthrottled'));
1987 $this->setRobotPolicy( 'noindex,follow' );
1988 $this->setArticleRelated( false );
1989 $this->enableClientCache( false );
1990 $this->mRedirect
= '';
1992 $this->setStatusCode(503);
1993 $this->addWikiMsg( 'actionthrottledtext' );
1995 $this->returnToMain( null, $this->getTitle() );
1999 * Show an "add new section" link?
2003 public function showNewSectionLink() {
2004 return $this->mNewSectionLink
;
2008 * Forcibly hide the new section link?
2012 public function forceHideNewSectionLink() {
2013 return $this->mHideNewSectionLink
;
2017 * Show a warning about slave lag
2019 * If the lag is higher than $wgSlaveLagCritical seconds,
2020 * then the warning is a bit more obvious. If the lag is
2021 * lower than $wgSlaveLagWarning, then no warning is shown.
2023 * @param int $lag Slave lag
2025 public function showLagWarning( $lag ) {
2026 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2027 if( $lag >= $wgSlaveLagWarning ) {
2028 $message = $lag < $wgSlaveLagCritical
2031 $warning = wfMsgExt( $message, 'parse', $lag );
2032 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2037 * Add a wikitext-formatted message to the output.
2038 * This is equivalent to:
2040 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2042 public function addWikiMsg( /*...*/ ) {
2043 $args = func_get_args();
2044 $name = array_shift( $args );
2045 $this->addWikiMsgArray( $name, $args );
2049 * Add a wikitext-formatted message to the output.
2050 * Like addWikiMsg() except the parameters are taken as an array
2051 * instead of a variable argument list.
2053 * $options is passed through to wfMsgExt(), see that function for details.
2055 public function addWikiMsgArray( $name, $args, $options = array() ) {
2056 $options[] = 'parse';
2057 $text = wfMsgExt( $name, $options, $args );
2058 $this->addHTML( $text );
2062 * This function takes a number of message/argument specifications, wraps them in
2063 * some overall structure, and then parses the result and adds it to the output.
2065 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2066 * on. The subsequent arguments may either be strings, in which case they are the
2067 * message names, or arrays, in which case the first element is the message name,
2068 * and subsequent elements are the parameters to that message.
2070 * The special named parameter 'options' in a message specification array is passed
2071 * through to the $options parameter of wfMsgExt().
2073 * Don't use this for messages that are not in users interface language.
2077 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2081 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2083 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2084 $msgSpecs = func_get_args();
2085 array_shift( $msgSpecs );
2086 $msgSpecs = array_values( $msgSpecs );
2088 foreach ( $msgSpecs as $n => $spec ) {
2090 if ( is_array( $spec ) ) {
2092 $name = array_shift( $args );
2093 if ( isset( $args['options'] ) ) {
2094 $options = $args['options'];
2095 unset( $args['options'] );
2101 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2103 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );