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();
19 // The most recent revision ID of any wikiPage script that is grouped in the script request
20 var $mLatestScriptRevID = 0;
22 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
23 var $mTemplateIds = array();
26 var $mSuppressQuickbar = false;
27 var $mOnloadHandler = '';
28 var $mDoNothing = false;
29 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
30 var $mIsArticleRelated = true;
31 protected $mParserOptions = null; // lazy initialised, use parserOptions()
32 var $mShowFeedLinks = false;
33 var $mFeedLinksAppendQuery = false;
34 var $mEnableClientCache = true;
35 var $mArticleBodyOnly = false;
37 var $mNewSectionLink = false;
38 var $mHideNewSectionLink = false;
39 var $mNoGallery = false;
40 var $mPageTitleActionText = '';
41 var $mParseWarnings = array();
42 var $mSquidMaxage = 0;
43 var $mRevisionId = null;
44 protected $mTitle = null;
47 * An array of stylesheet filenames (relative from skins path), with options
48 * for CSS media, IE conditions, and RTL/LTR direction.
49 * For internal use; add settings in the skin via $this->addStyle()
51 var $styles = array();
53 private $mIndexPolicy = 'index';
54 private $mFollowPolicy = 'follow';
58 * Initialise private variables
60 function __construct() {
61 global $wgAllowUserJs;
62 $this->mAllowUserJs
= $wgAllowUserJs;
65 public function redirect( $url, $responsecode = '302' ) {
66 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
67 $this->mRedirect
= str_replace( "\n", '', $url );
68 $this->mRedirectCode
= $responsecode;
71 public function getRedirect() {
72 return $this->mRedirect
;
76 * Set the HTTP status code to send with the output.
78 * @param int $statusCode
81 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
84 * Add a new <meta> tag
85 * To add an http-equiv meta tag, precede the name with "http:"
87 * @param $name tag name
88 * @param $val tag value
90 function addMeta( $name, $val ) {
91 array_push( $this->mMetatags
, array( $name, $val ) );
94 function addKeyword( $text ) {
95 if( is_array( $text )) {
96 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
98 array_push( $this->mKeywords
, $text );
101 function addScript( $script ) {
102 $this->mScripts
.= $script . "\n";
106 * Register and add a stylesheet from an extension directory.
107 * @param $url String path to sheet. Provide either a full url (beginning
108 * with 'http', etc) or a relative path from the document root
109 * (beginning with '/'). Otherwise it behaves identically to
110 * addStyle() and draws from the /skins folder.
112 public function addExtensionStyle( $url ) {
113 array_push( $this->mExtStyles
, $url );
117 * Add a JavaScript file out of skins/common, or a given relative path.
118 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
120 function addScriptFile( $file ) {
121 global $wgStylePath, $wgScript, $wgUser;
122 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
124 if( substr( $file, 0, 1 ) == '/' ) {
127 $path = "{$wgStylePath}/common/{$file}";
130 if( $wgEnableScriptLoader ) {
131 if( strpos( $path, $wgScript ) !== false ) {
132 $reqPath = str_replace( $wgScript . '?', '', $path );
133 $reqArgs = explode( '&', $reqPath );
136 foreach( $reqArgs as $arg ) {
137 list( $key, $var ) = explode( '=', $arg );
138 $reqSet[$key] = $var;
141 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
142 // Extract any extra parameters (for now just skin)
143 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' )
144 ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
145 $this->mScriptLoaderClassList
[] = 'WT:' . $reqSet['title'] . $ext_param ;
146 // Add the title revision to the key.
147 // If there is no title, we will just use $wgStyleVersion,
148 // which should be updated on the relevant commits.
149 $t = Title
::newFromText( $reqSet['title'] );
150 if( $t && $t->exists() ) {
151 if( $t->getLatestRevID() > $this->mLatestScriptRevID
)
152 $this->mLatestScriptRevID
= $t->getLatestRevID();
158 // If the class can be determined, add it to the class list to be loaded later
159 $js_class = $this->getJsClassFromPath( $path );
161 $this->mScriptLoaderClassList
[] = $js_class;
166 // If the script loader could not be used, just add the script to the header
167 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
171 * Add the core scripts that are included on every page, for later output into the header
173 function addCoreScripts2Top(){
174 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgEnableJS2system;
175 // @todo We should deprecate wikibits in favor of mv_embed and jQuery
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 the JavaScript class
198 * @return boolean False if the 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] )
205 ||
isset( $wgJSAutoloadLocalClasses[$js_class] ) )
207 if( $wgEnableScriptLoader ) {
208 // Register it with the script loader
209 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ) {
210 $this->mScriptLoaderClassList
[] = $js_class;
213 // Source the script directly
214 $path = $wgScriptPath . '/';
215 if( isset( $wgJSAutoloadClasses[$js_class] ) ) {
216 $path .= $wgJSAutoloadClasses[$js_class];
217 } elseif( isset( $wgJSAutoloadLocalClasses[$js_class] ) ) {
218 $path .= $wgJSAutoloadLocalClasses[$js_class];
220 $urlAppend = ( $wgDebugJavaScript ) ?
time() : $wgStyleVersion;
221 $this->addScript( Html
::linkedScript( "$path?$urlAppend" ) );
225 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
226 return false; // could not find the class
230 * Get the <script> tag which will invoke the script loader
231 * @param $classAry A class array which, if given, overrides $this->mScriptLoaderClassList
233 function getScriptLoaderJs( $classAry = array() ) {
234 global $wgRequest, $wgDebugJavaScript;
235 // If no class array was provided, use mScriptLoaderClassList
236 if( !count( $classAry ) ) {
237 $classAry = $this->mScriptLoaderClassList
;
239 $class_list = implode( ',', $classAry );
241 $debug_param = ( $wgDebugJavaScript ||
242 $wgRequest->getVal( 'debug' ) == 'true' ||
243 $wgRequest->getVal( 'debug' ) == '1' )
244 ?
'&debug=true' : '';
246 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) .
247 "?class={$class_list}{$debug_param}&" . $this->getURIDparam( $classAry) );
251 * Get the unique request ID parameter for the script-loader request
253 function getURIDparam( $classAry = array() ) {
254 global $wgDebugJavaScript, $wgStyleVersion, $IP, $wgScriptModifiedCheck;
255 if( $wgDebugJavaScript ) {
256 return 'urid=' . time();
259 if($wgScriptModifiedCheck) {
260 foreach( $classAry as $class ) {
261 $js_path = jsScriptLoader
::getJsPathFromClass( $class );
263 $cur_ftime = filemtime ( $IP ."/". $js_path );
264 if( $cur_ftime > $ftime )
269 $urid = "urid={$wgStyleVersion}";
271 // Add the latest revision ID if we have it
272 if($this->mLatestScriptRevID
!= 0 )
273 $urid .= "_{$this->mLatestScriptRevID}";
275 // Add the file modification time
284 * Given a script path, get the JS class name, or false if no such path is registered.
285 * @param $path string
287 function getJsClassFromPath( $path ) {
288 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
290 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
291 foreach( $scriptLoaderPaths as $js_class => $js_path ) {
292 $js_path = "{$wgScriptPath}/{$js_path}";
293 if( $path == $js_path )
300 * Add a self-contained script tag with the given contents
301 * @param string $script JavaScript text, no <script> tags
303 function addInlineScript( $script ) {
304 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
308 * Get all registered JS and CSS tags for the header.
310 function getScript() {
311 global $wgEnableScriptLoader;
312 if( $wgEnableScriptLoader ){
313 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
315 return $this->mScripts
. $this->getHeadItems();
319 function getHeadItems() {
321 foreach ( $this->mHeadItems
as $item ) {
327 function addHeadItem( $name, $value ) {
328 $this->mHeadItems
[$name] = $value;
331 function hasHeadItem( $name ) {
332 return isset( $this->mHeadItems
[$name] );
335 function setETag($tag) { $this->mETag
= $tag; }
336 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
337 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
339 function addLink( $linkarr ) {
340 # $linkarr should be an associative array of attributes. We'll escape on output.
341 array_push( $this->mLinktags
, $linkarr );
344 # Get all links added by extensions
345 function getExtStyle() {
346 return $this->mExtStyles
;
349 function addMetadataLink( $linkarr ) {
350 # note: buggy CC software only reads first "meta" link
351 static $haveMeta = false;
352 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
353 $this->addLink( $linkarr );
358 * checkLastModified tells the client to use the client-cached page if
359 * possible. If sucessful, the OutputPage is disabled so that
360 * any future call to OutputPage->output() have no effect.
362 * Side effect: sets mLastModified for Last-Modified header
364 * @return bool True iff cache-ok headers was sent.
366 function checkLastModified( $timestamp ) {
367 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
369 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
370 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
373 if( !$wgCachePages ) {
374 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
377 if( $wgUser->getOption( 'nocache' ) ) {
378 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
382 $timestamp = wfTimestamp( TS_MW
, $timestamp );
383 $modifiedTimes = array(
384 'page' => $timestamp,
385 'user' => $wgUser->getTouched(),
386 'epoch' => $wgCacheEpoch
388 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
390 $maxModified = max( $modifiedTimes );
391 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
393 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
394 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
400 foreach ( $modifiedTimes as $name => $value ) {
401 if ( $info !== '' ) {
404 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
407 # IE sends sizes after the date like this:
408 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
409 # this breaks strtotime().
410 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
412 wfSuppressWarnings(); // E_STRICT system time bitching
413 $clientHeaderTime = strtotime( $clientHeader );
415 if ( !$clientHeaderTime ) {
416 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
419 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
421 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
422 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
423 wfDebug( __METHOD__
. ": effective Last-Modified: " .
424 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
425 if( $clientHeaderTime < $maxModified ) {
426 wfDebug( __METHOD__
. ": STALE, $info\n", false );
431 # Give a 304 response code and disable body output
432 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
433 ini_set('zlib.output_compression', 0);
434 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
435 $this->sendCacheControl();
438 // Don't output a compressed blob when using ob_gzhandler;
439 // it's technically against HTTP spec and seems to confuse
440 // Firefox when the response gets split over two packets.
441 wfClearOutputBuffers();
446 function setPageTitleActionText( $text ) {
447 $this->mPageTitleActionText
= $text;
450 function getPageTitleActionText () {
451 if ( isset( $this->mPageTitleActionText
) ) {
452 return $this->mPageTitleActionText
;
457 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
459 * @param $policy string The literal string to output as the contents of
460 * the meta tag. Will be parsed according to the spec and output in
464 public function setRobotPolicy( $policy ) {
465 $policy = Article
::formatRobotPolicy( $policy );
467 if( isset( $policy['index'] ) ){
468 $this->setIndexPolicy( $policy['index'] );
470 if( isset( $policy['follow'] ) ){
471 $this->setFollowPolicy( $policy['follow'] );
476 * Set the index policy for the page, but leave the follow policy un-
479 * @param $policy string Either 'index' or 'noindex'.
482 public function setIndexPolicy( $policy ) {
483 $policy = trim( $policy );
484 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
485 $this->mIndexPolicy
= $policy;
490 * Set the follow policy for the page, but leave the index policy un-
493 * @param $policy string Either 'follow' or 'nofollow'.
496 public function setFollowPolicy( $policy ) {
497 $policy = trim( $policy );
498 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
499 $this->mFollowPolicy
= $policy;
504 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
506 public function setHTMLTitle( $name ) {
507 $this->mHTMLtitle
= $name;
511 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
512 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
513 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
514 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
516 public function setPageTitle( $name ) {
518 $name = $wgContLang->convert( $name, true );
519 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
520 # but leave "<i>foobar</i>" alone
521 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
522 $this->mPagetitle
= $nameWithTags;
524 $taction = $this->getPageTitleActionText();
525 if( !empty( $taction ) ) {
526 $name .= ' - '.$taction;
529 # change "<i>foo&bar</i>" to "foo&bar"
530 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
533 public function setTitle( $t ) {
537 public function getTitle() {
538 if ( $this->mTitle
instanceof Title
) {
539 return $this->mTitle
;
542 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
548 public function getHTMLTitle() { return $this->mHTMLtitle
; }
549 public function getPageTitle() { return $this->mPagetitle
; }
550 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
551 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
552 public function getSubtitle() { return $this->mSubtitle
; }
553 public function isArticle() { return $this->mIsarticle
; }
554 public function setPrintable() { $this->mPrintable
= true; }
555 public function isPrintable() { return $this->mPrintable
; }
556 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
557 public function isSyndicated() { return $this->mShowFeedLinks
; }
558 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
559 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
560 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
561 public function getOnloadHandler() { return $this->mOnloadHandler
; }
562 public function disable() { $this->mDoNothing
= true; }
563 public function isDisabled() { return $this->mDoNothing
; }
565 public function setArticleRelated( $v ) {
566 $this->mIsArticleRelated
= $v;
568 $this->mIsarticle
= false;
571 public function setArticleFlag( $v ) {
572 $this->mIsarticle
= $v;
574 $this->mIsArticleRelated
= $v;
578 public function isArticleRelated() { return $this->mIsArticleRelated
; }
580 public function getLanguageLinks() { return $this->mLanguageLinks
; }
581 public function addLanguageLinks($newLinkArray) {
582 $this->mLanguageLinks +
= $newLinkArray;
584 public function setLanguageLinks($newLinkArray) {
585 $this->mLanguageLinks
= $newLinkArray;
588 public function getCategoryLinks() {
589 return $this->mCategoryLinks
;
593 * Add an array of categories, with names in the keys
595 public function addCategoryLinks( $categories ) {
596 global $wgUser, $wgContLang;
598 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
602 # Add the links to a LinkBatch
603 $arr = array( NS_CATEGORY
=> $categories );
605 $lb->setArray( $arr );
607 # Fetch existence plus the hiddencat property
608 $dbr = wfGetDB( DB_SLAVE
);
609 $pageTable = $dbr->tableName( 'page' );
610 $where = $lb->constructSet( 'page', $dbr );
611 $propsTable = $dbr->tableName( 'page_props' );
612 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
613 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
614 $res = $dbr->query( $sql, __METHOD__
);
616 # Add the results to the link cache
617 $lb->addResultToCache( LinkCache
::singleton(), $res );
619 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
620 $categories = array_combine( array_keys( $categories ),
621 array_fill( 0, count( $categories ), 'normal' ) );
623 # Mark hidden categories
624 foreach ( $res as $row ) {
625 if ( isset( $row->pp_value
) ) {
626 $categories[$row->page_title
] = 'hidden';
630 # Add the remaining categories to the skin
631 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
632 $sk = $wgUser->getSkin();
633 foreach ( $categories as $category => $type ) {
634 $origcategory = $category;
635 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
636 $wgContLang->findVariantLink( $category, $title, true );
637 if ( $category != $origcategory )
638 if ( array_key_exists( $category, $categories ) )
640 $text = $wgContLang->convertHtml( $title->getText() );
641 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
646 public function setCategoryLinks($categories) {
647 $this->mCategoryLinks
= array();
648 $this->addCategoryLinks($categories);
651 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
652 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
654 public function disallowUserJs() { $this->mAllowUserJs
= false; }
655 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
657 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
658 public function addHTML( $text ) { $this->mBodytext
.= $text; }
659 public function clearHTML() { $this->mBodytext
= ''; }
660 public function getHTML() { return $this->mBodytext
; }
661 public function debug( $text ) { $this->mDebugtext
.= $text; }
664 public function setParserOptions( $options ) {
665 wfDeprecated( __METHOD__
);
666 return $this->parserOptions( $options );
669 public function parserOptions( $options = null ) {
670 if ( !$this->mParserOptions
) {
671 $this->mParserOptions
= new ParserOptions
;
673 return wfSetVar( $this->mParserOptions
, $options );
677 * Set the revision ID which will be seen by the wiki text parser
678 * for things such as embedded {{REVISIONID}} variable use.
679 * @param mixed $revid an integer, or NULL
680 * @return mixed previous value
682 public function setRevisionId( $revid ) {
683 $val = is_null( $revid ) ?
null : intval( $revid );
684 return wfSetVar( $this->mRevisionId
, $val );
687 public function getRevisionId() {
688 return $this->mRevisionId
;
692 * Convert wikitext to HTML and add it to the buffer
693 * Default assumes that the current page title will
696 * @param string $text
697 * @param bool $linestart
699 public function addWikiText( $text, $linestart = true ) {
700 $title = $this->getTitle(); // Work arround E_STRICT
701 $this->addWikiTextTitle( $text, $title, $linestart );
704 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
705 $this->addWikiTextTitle($text, $title, $linestart);
708 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
709 $this->addWikiTextTitle( $text, $title, $linestart, true );
712 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
715 wfProfileIn( __METHOD__
);
717 wfIncrStats( 'pcache_not_possible' );
719 $popts = $this->parserOptions();
720 $oldTidy = $popts->setTidy( $tidy );
722 $parserOutput = $wgParser->parse( $text, $title, $popts,
723 $linestart, true, $this->mRevisionId
);
725 $popts->setTidy( $oldTidy );
727 $this->addParserOutput( $parserOutput );
729 wfProfileOut( __METHOD__
);
734 * @param ParserOutput object &$parserOutput
736 public function addParserOutputNoText( &$parserOutput ) {
737 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
739 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
740 $this->addCategoryLinks( $parserOutput->getCategories() );
741 $this->mNewSectionLink
= $parserOutput->getNewSection();
742 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
744 $this->mParseWarnings
= $parserOutput->getWarnings();
745 if ( $parserOutput->getCacheTime() == -1 ) {
746 $this->enableClientCache( false );
748 $this->mNoGallery
= $parserOutput->getNoGallery();
749 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
751 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
752 if ( isset( $this->mTemplateIds
[$ns] ) ) {
753 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
755 $this->mTemplateIds
[$ns] = $dbks;
759 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
760 $this->setPageTitle( $dt );
761 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
762 $this->setPageTitle( $title );
764 // Hooks registered in the object
765 global $wgParserOutputHooks;
766 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
767 list( $hookName, $data ) = $hookInfo;
768 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
769 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
773 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
778 * @param ParserOutput &$parserOutput
780 function addParserOutput( &$parserOutput ) {
781 $this->addParserOutputNoText( $parserOutput );
782 $text = $parserOutput->getText();
783 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
784 $this->addHTML( $text );
788 * Add wikitext to the buffer, assuming that this is the primary text for a page view
789 * Saves the text into the parser cache if possible.
791 * @param string $text
792 * @param Article $article
794 * @deprecated Use Article::outputWikitext
796 public function addPrimaryWikiText( $text, $article, $cache = true ) {
799 wfDeprecated( __METHOD__
);
801 $popts = $this->parserOptions();
802 $popts->setTidy(true);
803 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
804 $popts, true, true, $this->mRevisionId
);
805 $popts->setTidy(false);
806 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
807 $parserCache = ParserCache
::singleton();
808 $parserCache->save( $parserOutput, $article, $popts);
811 $this->addParserOutput( $parserOutput );
815 * @deprecated use addWikiTextTidy()
817 public function addSecondaryWikiText( $text, $linestart = true ) {
818 wfDeprecated( __METHOD__
);
819 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
823 * Add wikitext with tidy enabled
825 public function addWikiTextTidy( $text, $linestart = true ) {
826 $title = $this->getTitle();
827 $this->addWikiTextTitleTidy($text, $title, $linestart);
832 * Add the output of a QuickTemplate to the output buffer
834 * @param QuickTemplate $template
836 public function addTemplate( &$template ) {
838 $template->execute();
839 $this->addHTML( ob_get_contents() );
844 * Parse wikitext and return the HTML.
846 * @param string $text
847 * @param bool $linestart Is this the start of a line?
848 * @param bool $interface ??
850 public function parse( $text, $linestart = true, $interface = false ) {
852 if( is_null( $this->getTitle() ) ) {
853 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
855 $popts = $this->parserOptions();
856 if ( $interface) { $popts->setInterfaceMessage(true); }
857 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
858 $linestart, true, $this->mRevisionId
);
859 if ( $interface) { $popts->setInterfaceMessage(false); }
860 return $parserOutput->getText();
863 /** Parse wikitext, strip paragraphs, and return the HTML. */
864 public function parseInline( $text, $linestart = true, $interface = false ) {
865 $parsed = $this->parse( $text, $linestart, $interface );
868 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
876 * @param Article $article
881 * @return bool True if successful, else false.
883 public function tryParserCache( &$article ) {
884 wfDeprecated( __METHOD__
);
885 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
887 if ($parserOutput !== false) {
888 $this->addParserOutput( $parserOutput );
896 * @param int $maxage Maximum cache time on the Squid, in seconds.
898 public function setSquidMaxage( $maxage ) {
899 $this->mSquidMaxage
= $maxage;
903 * Use enableClientCache(false) to force it to send nocache headers
906 public function enableClientCache( $state ) {
907 return wfSetVar( $this->mEnableClientCache
, $state );
910 function getCacheVaryCookies() {
911 global $wgCookiePrefix, $wgCacheVaryCookies;
913 if ( $cookies === null ) {
914 $cookies = array_merge(
916 "{$wgCookiePrefix}Token",
917 "{$wgCookiePrefix}LoggedOut",
922 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
927 function uncacheableBecauseRequestVars() {
929 return $wgRequest->getText('useskin', false) === false
930 && $wgRequest->getText('uselang', false) === false;
934 * Check if the request has a cache-varying cookie header
935 * If it does, it's very important that we don't allow public caching
937 function haveCacheVaryCookies() {
939 $cookieHeader = $wgRequest->getHeader( 'cookie' );
940 if ( $cookieHeader === false ) {
943 $cvCookies = $this->getCacheVaryCookies();
944 foreach ( $cvCookies as $cookieName ) {
945 # Check for a simple string match, like the way squid does it
946 if ( strpos( $cookieHeader, $cookieName ) ) {
947 wfDebug( __METHOD__
.": found $cookieName\n" );
951 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
955 /** Get a complete X-Vary-Options header */
956 public function getXVO() {
957 $cvCookies = $this->getCacheVaryCookies();
958 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
960 foreach ( $cvCookies as $cookieName ) {
966 $xvo .= 'string-contains=' . $cookieName;
971 public function sendCacheControl() {
972 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
974 $response = $wgRequest->response();
975 if ($wgUseETag && $this->mETag
)
976 $response->header("ETag: $this->mETag");
978 # don't serve compressed data to clients who can't handle it
979 # maintain different caches for logged-in users and non-logged in ones
980 $response->header( 'Vary: Accept-Encoding, Cookie' );
983 # Add an X-Vary-Options header for Squid with Wikimedia patches
984 $response->header( $this->getXVO() );
987 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
988 if( $wgUseSquid && session_id() == '' &&
989 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
992 # We'll purge the proxy cache explicitly, but require end user agents
993 # to revalidate against the proxy on each visit.
994 # Surrogate-Control controls our Squid, Cache-Control downstream caches
995 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
996 # start with a shorter timeout for initial testing
997 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
998 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
999 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1001 # We'll purge the proxy cache for anons explicitly, but require end user agents
1002 # to revalidate against the proxy on each visit.
1003 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1004 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1005 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1006 # start with a shorter timeout for initial testing
1007 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1008 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1011 # We do want clients to cache if they can, but they *must* check for updates
1012 # on revisiting the page.
1013 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1014 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1015 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1017 if($this->mLastModified
) {
1018 $response->header( "Last-Modified: {$this->mLastModified}" );
1021 wfDebug( __METHOD__
. ": no caching **\n", false );
1023 # In general, the absence of a last modified header should be enough to prevent
1024 # the client from using its cache. We send a few other things just to make sure.
1025 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1026 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1027 $response->header( 'Pragma: no-cache' );
1032 * Finally, all the text has been munged and accumulated into
1033 * the object, let's actually output it:
1035 public function output() {
1036 global $wgUser, $wgOutputEncoding, $wgRequest;
1037 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1038 global $wgUseAjax, $wgAjaxWatch;
1039 global $wgEnableMWSuggest, $wgUniversalEditButton;
1042 if( $this->mDoNothing
){
1045 wfProfileIn( __METHOD__
);
1046 if ( '' != $this->mRedirect
) {
1047 # Standards require redirect URLs to be absolute
1048 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1049 if( $this->mRedirectCode
== '301') {
1050 if( !$wgDebugRedirects ) {
1051 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1053 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1055 $this->sendCacheControl();
1057 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1058 if( $wgDebugRedirects ) {
1059 $url = htmlspecialchars( $this->mRedirect
);
1060 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1061 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1062 print "</body>\n</html>\n";
1064 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1066 wfProfileOut( __METHOD__
);
1069 elseif ( $this->mStatusCode
)
1071 $statusMessage = array(
1073 101 => 'Switching Protocols',
1074 102 => 'Processing',
1078 203 => 'Non-Authoritative Information',
1079 204 => 'No Content',
1080 205 => 'Reset Content',
1081 206 => 'Partial Content',
1082 207 => 'Multi-Status',
1083 300 => 'Multiple Choices',
1084 301 => 'Moved Permanently',
1087 304 => 'Not Modified',
1089 307 => 'Temporary Redirect',
1090 400 => 'Bad Request',
1091 401 => 'Unauthorized',
1092 402 => 'Payment Required',
1095 405 => 'Method Not Allowed',
1096 406 => 'Not Acceptable',
1097 407 => 'Proxy Authentication Required',
1098 408 => 'Request Timeout',
1101 411 => 'Length Required',
1102 412 => 'Precondition Failed',
1103 413 => 'Request Entity Too Large',
1104 414 => 'Request-URI Too Large',
1105 415 => 'Unsupported Media Type',
1106 416 => 'Request Range Not Satisfiable',
1107 417 => 'Expectation Failed',
1108 422 => 'Unprocessable Entity',
1110 424 => 'Failed Dependency',
1111 500 => 'Internal Server Error',
1112 501 => 'Not Implemented',
1113 502 => 'Bad Gateway',
1114 503 => 'Service Unavailable',
1115 504 => 'Gateway Timeout',
1116 505 => 'HTTP Version Not Supported',
1117 507 => 'Insufficient Storage'
1120 if ( $statusMessage[$this->mStatusCode
] )
1121 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1124 $sk = $wgUser->getSkin();
1126 // Add our core scripts to output
1127 $this->addCoreScripts2Top();
1130 $this->addScriptFile( 'ajax.js' );
1132 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1134 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1135 $this->addScriptFile( 'ajaxwatch.js' );
1138 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1139 $this->addScriptFile( 'mwsuggest.js' );
1143 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1144 $this->addScriptFile( 'rightclickedit.js' );
1147 global $wgUseAJAXCategories;
1148 if ($wgUseAJAXCategories) {
1149 $this->addScriptClass( 'ajaxCategories' );
1152 if( $wgUniversalEditButton ) {
1153 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1154 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1155 // Original UniversalEditButton
1156 $msg = wfMsg('edit');
1157 $this->addLink( array(
1158 'rel' => 'alternate',
1159 'type' => 'application/x-wiki',
1161 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1163 // Alternate edit link
1164 $this->addLink( array(
1167 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1172 # Buffer output; final headers may depend on later processing
1175 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1176 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1178 if ($this->mArticleBodyOnly
) {
1179 $this->out($this->mBodytext
);
1181 // Hook that allows last minute changes to the output page, e.g.
1182 // adding of CSS or Javascript by extensions.
1183 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1185 wfProfileIn( 'Output-skin' );
1186 $sk->outputPage( $this );
1187 wfProfileOut( 'Output-skin' );
1190 $this->sendCacheControl();
1192 wfProfileOut( __METHOD__
);
1196 * Actually output something with print(). Performs an iconv to the
1197 * output encoding, if needed.
1198 * @param string $ins The string to output
1200 public function out( $ins ) {
1201 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1202 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1205 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1206 if ( false === $outs ) { $outs = $ins; }
1214 public static function setEncodings() {
1215 global $wgInputEncoding, $wgOutputEncoding;
1218 $wgInputEncoding = strtolower( $wgInputEncoding );
1220 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1221 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1224 $wgOutputEncoding = $wgInputEncoding;
1228 * Deprecated, use wfReportTime() instead.
1232 public function reportTime() {
1233 wfDeprecated( __METHOD__
);
1234 $time = wfReportTime();
1239 * Produce a "user is blocked" page.
1241 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1244 function blockedPage( $return = true ) {
1245 global $wgUser, $wgContLang, $wgLang;
1247 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1248 $this->setRobotPolicy( 'noindex,nofollow' );
1249 $this->setArticleRelated( false );
1251 $name = User
::whoIs( $wgUser->blockedBy() );
1252 $reason = $wgUser->blockedFor();
1253 if( $reason == '' ) {
1254 $reason = wfMsg( 'blockednoreason' );
1256 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1259 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1261 $blockid = $wgUser->mBlock
->mId
;
1263 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1264 if ( $blockExpiry == 'infinity' ) {
1265 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1266 // Search for localization in 'ipboptions'
1267 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1268 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1269 if ( strpos( $option, ":" ) === false )
1271 list( $show, $value ) = explode( ":", $option );
1272 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1273 $blockExpiry = $show;
1278 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1281 if ( $wgUser->mBlock
->mAuto
) {
1282 $msg = 'autoblockedtext';
1284 $msg = 'blockedtext';
1287 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1288 * This could be a username, an ip range, or a single ip. */
1289 $intended = $wgUser->mBlock
->mAddress
;
1291 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1293 # Don't auto-return to special pages
1295 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1296 $this->returnToMain( null, $return );
1301 * Output a standard error page
1303 * @param string $title Message key for page title
1304 * @param string $msg Message key for page text
1305 * @param array $params Message parameters
1307 public function showErrorPage( $title, $msg, $params = array() ) {
1308 if ( $this->getTitle() ) {
1309 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1311 $this->setPageTitle( wfMsg( $title ) );
1312 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1313 $this->setRobotPolicy( 'noindex,nofollow' );
1314 $this->setArticleRelated( false );
1315 $this->enableClientCache( false );
1316 $this->mRedirect
= '';
1317 $this->mBodytext
= '';
1319 array_unshift( $params, 'parse' );
1320 array_unshift( $params, $msg );
1321 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1323 $this->returnToMain();
1327 * Output a standard permission error page
1329 * @param array $errors Error message keys
1331 public function showPermissionsErrorPage( $errors, $action = null )
1333 $this->mDebugtext
.= 'Original title: ' .
1334 $this->getTitle()->getPrefixedText() . "\n";
1335 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1336 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1337 $this->setRobotPolicy( 'noindex,nofollow' );
1338 $this->setArticleRelated( false );
1339 $this->enableClientCache( false );
1340 $this->mRedirect
= '';
1341 $this->mBodytext
= '';
1342 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1346 public function errorpage( $title, $msg ) {
1347 wfDeprecated( __METHOD__
);
1348 throw new ErrorPageError( $title, $msg );
1352 * Display an error page indicating that a given version of MediaWiki is
1353 * required to use it
1355 * @param mixed $version The version of MediaWiki needed to use the page
1357 public function versionRequired( $version ) {
1358 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1359 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1360 $this->setRobotPolicy( 'noindex,nofollow' );
1361 $this->setArticleRelated( false );
1362 $this->mBodytext
= '';
1364 $this->addWikiMsg( 'versionrequiredtext', $version );
1365 $this->returnToMain();
1369 * Display an error page noting that a given permission bit is required.
1371 * @param string $permission key required
1373 public function permissionRequired( $permission ) {
1376 $this->setPageTitle( wfMsg( 'badaccess' ) );
1377 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1378 $this->setRobotPolicy( 'noindex,nofollow' );
1379 $this->setArticleRelated( false );
1380 $this->mBodytext
= '';
1382 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1383 User
::getGroupsWithPermission( $permission ) );
1385 $this->addWikiMsg( 'badaccess-groups',
1386 $wgLang->commaList( $groups ),
1389 $this->addWikiMsg( 'badaccess-group0' );
1391 $this->returnToMain();
1395 * Use permissionRequired.
1398 public function sysopRequired() {
1399 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1403 * Use permissionRequired.
1406 public function developerRequired() {
1407 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1411 * Produce the stock "please login to use the wiki" page
1413 public function loginToUse() {
1414 global $wgUser, $wgContLang;
1416 if( $wgUser->isLoggedIn() ) {
1417 $this->permissionRequired( 'read' );
1421 $skin = $wgUser->getSkin();
1423 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1424 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1425 $this->setRobotPolicy( 'noindex,nofollow' );
1426 $this->setArticleFlag( false );
1428 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1429 $loginLink = $skin->link(
1431 wfMsgHtml( 'loginreqlink' ),
1433 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1434 array( 'known', 'noclasses' )
1436 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1437 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1439 # Don't return to the main page if the user can't read it
1440 # otherwise we'll end up in a pointless loop
1441 $mainPage = Title
::newMainPage();
1442 if( $mainPage->userCanRead() )
1443 $this->returnToMain( null, $mainPage );
1447 public function databaseError( $fname, $sql, $error, $errno ) {
1448 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1452 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1453 * @return string The wikitext error-messages, formatted into a list.
1455 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1456 if ($action == null) {
1457 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1460 $action_desc = wfMsgNoTrans( "action-$action" );
1461 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1464 if (count( $errors ) > 1) {
1465 $text .= '<ul class="permissions-errors">' . "\n";
1467 foreach( $errors as $error )
1470 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1475 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1482 * Display a page stating that the Wiki is in read-only mode,
1483 * and optionally show the source of the page that the user
1484 * was trying to edit. Should only be called (for this
1485 * purpose) after wfReadOnly() has returned true.
1487 * For historical reasons, this function is _also_ used to
1488 * show the error message when a user tries to edit a page
1489 * they are not allowed to edit. (Unless it's because they're
1490 * blocked, then we show blockedPage() instead.) In this
1491 * case, the second parameter should be set to true and a list
1492 * of reasons supplied as the third parameter.
1494 * @todo Needs to be split into multiple functions.
1496 * @param string $source Source code to show (or null).
1497 * @param bool $protected Is this a permissions error?
1498 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1500 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1502 $skin = $wgUser->getSkin();
1504 $this->setRobotPolicy( 'noindex,nofollow' );
1505 $this->setArticleRelated( false );
1507 // If no reason is given, just supply a default "I can't let you do
1508 // that, Dave" message. Should only occur if called by legacy code.
1509 if ( $protected && empty($reasons) ) {
1510 $reasons[] = array( 'badaccess-group0' );
1513 if ( !empty($reasons) ) {
1514 // Permissions error
1516 $this->setPageTitle( wfMsg( 'viewsource' ) );
1525 array( 'known', 'noclasses' )
1530 $this->setPageTitle( wfMsg( 'badaccess' ) );
1532 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1534 // Wiki is read only
1535 $this->setPageTitle( wfMsg( 'readonly' ) );
1536 $reason = wfReadOnlyReason();
1537 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1540 // Show source, if supplied
1541 if( is_string( $source ) ) {
1542 $this->addWikiMsg( 'viewsourcetext' );
1543 $text = Xml
::openElement( 'textarea',
1544 array( 'id' => 'wpTextbox1',
1545 'name' => 'wpTextbox1',
1546 'cols' => $wgUser->getOption( 'cols' ),
1547 'rows' => $wgUser->getOption( 'rows' ),
1548 'readonly' => 'readonly' ) );
1549 $text .= htmlspecialchars( $source );
1550 $text .= Xml
::closeElement( 'textarea' );
1551 $this->addHTML( $text );
1553 // Show templates used by this article
1554 $skin = $wgUser->getSkin();
1555 $article = new Article( $this->getTitle() );
1556 $this->addHTML( "<div class='templatesUsed'>
1557 {$skin->formatTemplates( $article->getUsedTemplates() )}
1562 # If the title doesn't exist, it's fairly pointless to print a return
1563 # link to it. After all, you just tried editing it and couldn't, so
1564 # what's there to do there?
1565 if( $this->getTitle()->exists() ) {
1566 $this->returnToMain( null, $this->getTitle() );
1571 public function fatalError( $message ) {
1572 wfDeprecated( __METHOD__
);
1573 throw new FatalError( $message );
1577 public function unexpectedValueError( $name, $val ) {
1578 wfDeprecated( __METHOD__
);
1579 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1583 public function fileCopyError( $old, $new ) {
1584 wfDeprecated( __METHOD__
);
1585 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1589 public function fileRenameError( $old, $new ) {
1590 wfDeprecated( __METHOD__
);
1591 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1595 public function fileDeleteError( $name ) {
1596 wfDeprecated( __METHOD__
);
1597 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1601 public function fileNotFoundError( $name ) {
1602 wfDeprecated( __METHOD__
);
1603 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1606 public function showFatalError( $message ) {
1607 $this->setPageTitle( wfMsg( "internalerror" ) );
1608 $this->setRobotPolicy( "noindex,nofollow" );
1609 $this->setArticleRelated( false );
1610 $this->enableClientCache( false );
1611 $this->mRedirect
= '';
1612 $this->mBodytext
= $message;
1615 public function showUnexpectedValueError( $name, $val ) {
1616 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1619 public function showFileCopyError( $old, $new ) {
1620 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1623 public function showFileRenameError( $old, $new ) {
1624 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1627 public function showFileDeleteError( $name ) {
1628 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1631 public function showFileNotFoundError( $name ) {
1632 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1636 * Add a "return to" link pointing to a specified title
1638 * @param Title $title Title to link
1639 * @param string $query Query string
1641 public function addReturnTo( $title, $query = array() ) {
1643 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1644 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1645 $title, null, array(), $query ) );
1646 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1650 * Add a "return to" link pointing to a specified title,
1651 * or the title indicated in the request, or else the main page
1653 * @param null $unused No longer used
1654 * @param Title $returnto Title to return to
1656 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1659 if ( $returnto == null ) {
1660 $returnto = $wgRequest->getText( 'returnto' );
1663 if ( $returntoquery == null ) {
1664 $returntoquery = $wgRequest->getText( 'returntoquery' );
1667 if ( '' === $returnto ) {
1668 $returnto = Title
::newMainPage();
1671 if ( is_object( $returnto ) ) {
1672 $titleObj = $returnto;
1674 $titleObj = Title
::newFromText( $returnto );
1676 if ( !is_object( $titleObj ) ) {
1677 $titleObj = Title
::newMainPage();
1680 $this->addReturnTo( $titleObj, $returntoquery );
1684 * @return string The doctype, opening <html>, and head element.
1686 public function headElement( Skin
$sk ) {
1687 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1688 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1689 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1691 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1692 if ( $sk->commonPrintStylesheet() ) {
1693 $this->addStyle( 'common/wikiprintable.css', 'print' );
1695 $sk->setupUserCss( $this );
1699 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1700 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1703 if ( '' == $this->getHTMLTitle() ) {
1704 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1707 $dir = $wgContLang->getDir();
1710 $ret .= "<!doctype html>\n";
1711 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1713 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1714 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1715 foreach($wgXhtmlNamespaces as $tag => $ns) {
1716 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1718 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1722 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1723 $ret .= implode( "\n", array(
1724 $this->getHeadLinks(),
1725 $this->buildCssLinks(),
1726 $sk->getHeadScripts( $this ),
1727 $this->getHeadItems(),
1730 $ret .= Html
::inlineStyle( $sk->usercss
);
1733 if( $wgEnableScriptLoader )
1734 $ret .= $this->getScriptLoaderJs();
1736 if ($wgUseTrackbacks && $this->isArticleRelated())
1737 $ret .= $this->getTitle()->trackbackRDF();
1739 $ret .= "</head>\n";
1743 protected function addDefaultMeta() {
1744 global $wgVersion, $wgHtml5;
1746 static $called = false;
1748 # Don't run this twice
1754 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1756 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1758 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1759 if( $p !== 'index,follow' ) {
1760 // http://www.robotstxt.org/wc/meta-user.html
1761 // Only show if it's different from the default robots policy
1762 $this->addMeta( 'robots', $p );
1765 if ( count( $this->mKeywords
) > 0 ) {
1767 "/<.*?" . ">/" => '',
1770 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1775 * @return string HTML tag links to be put in the header.
1777 public function getHeadLinks() {
1778 global $wgRequest, $wgFeed;
1780 // Ideally this should happen earlier, somewhere. :P
1781 $this->addDefaultMeta();
1785 foreach ( $this->mMetatags
as $tag ) {
1786 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1788 $tag[0] = substr( $tag[0], 5 );
1792 $tags[] = Xml
::element( 'meta',
1795 'content' => $tag[1] ) );
1797 foreach ( $this->mLinktags
as $tag ) {
1798 $tags[] = Xml
::element( 'link', $tag );
1802 foreach( $this->getSyndicationLinks() as $format => $link ) {
1803 # Use the page name for the title (accessed through $wgTitle since
1804 # there's no other way). In principle, this could lead to issues
1805 # with having the same name for different feeds corresponding to
1806 # the same page, but we can't avoid that at this low a level.
1808 $tags[] = $this->feedLink(
1811 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1814 # Recent changes feed should appear on every page (except recentchanges,
1815 # that would be redundant). Put it after the per-page feed to avoid
1816 # changing existing behavior. It's still available, probably via a
1817 # menu in your browser. Some sites might have a different feed they'd
1818 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1819 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1820 # If so, use it instead.
1822 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1823 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1825 if ( $wgOverrideSiteFeed ) {
1826 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1827 $tags[] = $this->feedLink (
1829 htmlspecialchars( $feedUrl ),
1830 wfMsg( "site-{$type}-feed", $wgSitename ) );
1833 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1834 foreach( $wgFeedClasses as $format => $class ) {
1835 $tags[] = $this->feedLink(
1837 $rctitle->getLocalURL( "feed={$format}" ),
1838 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1843 return implode( "\n", $tags ) . "\n";
1847 * Return URLs for each supported syndication format for this page.
1848 * @return array associating format keys with URLs
1850 public function getSyndicationLinks() {
1851 global $wgFeedClasses;
1854 if( $this->isSyndicated() ) {
1855 if( is_string( $this->getFeedAppendQuery() ) ) {
1856 $appendQuery = "&" . $this->getFeedAppendQuery();
1861 foreach( $wgFeedClasses as $format => $class ) {
1862 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1869 * Generate a <link rel/> for an RSS feed.
1871 private function feedLink( $type, $url, $text ) {
1872 return Xml
::element( 'link', array(
1873 'rel' => 'alternate',
1874 'type' => "application/$type+xml",
1880 * Add a local or specified stylesheet, with the given media options.
1881 * Meant primarily for internal use...
1883 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1884 * @param $conditional -- for IE conditional comments, specifying an IE version
1885 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1887 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1889 // Even though we expect the media type to be lowercase, but here we
1890 // force it to lowercase to be safe.
1892 $options['media'] = $media;
1894 $options['condition'] = $condition;
1896 $options['dir'] = $dir;
1897 $this->styles
[$style] = $options;
1901 * Adds inline CSS styles
1902 * @param $style_css Mixed: inline CSS
1904 public function addInlineStyle( $style_css ){
1905 $this->mScripts
.= Html
::inlineStyle( $style_css );
1909 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1910 * These will be applied to various media & IE conditionals.
1912 public function buildCssLinks() {
1914 foreach( $this->styles
as $file => $options ) {
1915 $link = $this->styleLink( $file, $options );
1920 return implode( "\n", $links );
1923 protected function styleLink( $style, $options ) {
1926 if( isset( $options['dir'] ) ) {
1928 $siteDir = $wgContLang->getDir();
1929 if( $siteDir != $options['dir'] )
1933 if( isset( $options['media'] ) ) {
1934 $media = $this->transformCssMedia( $options['media'] );
1935 if( is_null( $media ) ) {
1942 if( substr( $style, 0, 1 ) == '/' ||
1943 substr( $style, 0, 5 ) == 'http:' ||
1944 substr( $style, 0, 6 ) == 'https:' ) {
1947 global $wgStylePath, $wgStyleVersion;
1948 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1951 $link = Html
::linkedStyle( $url, $media );
1953 if( isset( $options['condition'] ) ) {
1954 $condition = htmlspecialchars( $options['condition'] );
1955 $link = "<!--[if $condition]>$link<![endif]-->";
1960 function transformCssMedia( $media ) {
1961 global $wgRequest, $wgHandheldForIPhone;
1963 // Switch in on-screen display for media testing
1965 'printable' => 'print',
1966 'handheld' => 'handheld',
1968 foreach( $switches as $switch => $targetMedia ) {
1969 if( $wgRequest->getBool( $switch ) ) {
1970 if( $media == $targetMedia ) {
1972 } elseif( $media == 'screen' ) {
1978 // Expand longer media queries as iPhone doesn't grok 'handheld'
1979 if( $wgHandheldForIPhone ) {
1980 $mediaAliases = array(
1981 'screen' => 'screen and (min-device-width: 481px)',
1982 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1985 if( isset( $mediaAliases[$media] ) ) {
1986 $media = $mediaAliases[$media];
1994 * Turn off regular page output and return an error reponse
1995 * for when rate limiting has triggered.
1997 public function rateLimited() {
1999 $this->setPageTitle(wfMsg('actionthrottled'));
2000 $this->setRobotPolicy( 'noindex,follow' );
2001 $this->setArticleRelated( false );
2002 $this->enableClientCache( false );
2003 $this->mRedirect
= '';
2005 $this->setStatusCode(503);
2006 $this->addWikiMsg( 'actionthrottledtext' );
2008 $this->returnToMain( null, $this->getTitle() );
2012 * Show an "add new section" link?
2016 public function showNewSectionLink() {
2017 return $this->mNewSectionLink
;
2021 * Forcibly hide the new section link?
2025 public function forceHideNewSectionLink() {
2026 return $this->mHideNewSectionLink
;
2030 * Show a warning about slave lag
2032 * If the lag is higher than $wgSlaveLagCritical seconds,
2033 * then the warning is a bit more obvious. If the lag is
2034 * lower than $wgSlaveLagWarning, then no warning is shown.
2036 * @param int $lag Slave lag
2038 public function showLagWarning( $lag ) {
2039 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2040 if( $lag >= $wgSlaveLagWarning ) {
2041 $message = $lag < $wgSlaveLagCritical
2044 $warning = wfMsgExt( $message, 'parse', $lag );
2045 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2050 * Add a wikitext-formatted message to the output.
2051 * This is equivalent to:
2053 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2055 public function addWikiMsg( /*...*/ ) {
2056 $args = func_get_args();
2057 $name = array_shift( $args );
2058 $this->addWikiMsgArray( $name, $args );
2062 * Add a wikitext-formatted message to the output.
2063 * Like addWikiMsg() except the parameters are taken as an array
2064 * instead of a variable argument list.
2066 * $options is passed through to wfMsgExt(), see that function for details.
2068 public function addWikiMsgArray( $name, $args, $options = array() ) {
2069 $options[] = 'parse';
2070 $text = wfMsgExt( $name, $options, $args );
2071 $this->addHTML( $text );
2075 * This function takes a number of message/argument specifications, wraps them in
2076 * some overall structure, and then parses the result and adds it to the output.
2078 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2079 * on. The subsequent arguments may either be strings, in which case they are the
2080 * message names, or arrays, in which case the first element is the message name,
2081 * and subsequent elements are the parameters to that message.
2083 * The special named parameter 'options' in a message specification array is passed
2084 * through to the $options parameter of wfMsgExt().
2086 * Don't use this for messages that are not in users interface language.
2090 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2094 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2096 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2097 $msgSpecs = func_get_args();
2098 array_shift( $msgSpecs );
2099 $msgSpecs = array_values( $msgSpecs );
2101 foreach ( $msgSpecs as $n => $spec ) {
2103 if ( is_array( $spec ) ) {
2105 $name = array_shift( $args );
2106 if ( isset( $args['options'] ) ) {
2107 $options = $args['options'];
2108 unset( $args['options'] );
2114 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2116 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );