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 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
20 var $mInlineMsg = 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 $wgEnableScriptLoader, $wgScriptPath;
123 if( substr( $file, 0, 1 ) == '/' ) {
126 $path = "{$wgStylePath}/common/{$file}";
129 // If the class can be determined, use the addScriptClass method
130 $js_class = $this->getJsClassFromPath( $path );
132 $this->addScriptClass( $js_class );
136 //do checks for wiki-titles
137 if( strpos( $path, $wgScript ) !== false ) {
138 $reqPath = str_replace( $wgScript . '?', '', $path );
139 $reqArgs = explode( '&', $reqPath );
142 foreach( $reqArgs as $arg ) {
143 list( $key, $var ) = explode( '=', $arg );
144 $reqSet[$key] = $var;
147 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
148 $jsTitleClass = 'WT:' . $reqSet['title'];
149 if( $wgEnableScriptLoader ) {
150 // Extract any extra parameters (for now just skin)
151 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' )
152 ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
153 $this->mScriptLoaderClassList
[] = $jsTitleClass . $ext_param ;
156 $this->addScript( Html
::linkedScript(
157 wfAppendQuery( $path, $this->getURIDparam( $jsTitleClass ) )
164 // If the script loader could not be used, just add the script to the header
165 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
169 * Add the core scripts that are included on every page, for later output into the header
171 function addCoreScripts2Top(){
172 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgEnableJS2system;
173 // @todo We should deprecate wikibits in favor of mv_embed and jQuery
175 if( $wgEnableJS2system ){
176 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
178 $core_classes = array( 'wikibits' );
181 if( $wgEnableScriptLoader ){
182 //add core to top of mScripts
183 $this->mScripts
= $this->getScriptLoaderJs( $core_classes ) . $this->mScripts
;
186 //make sure scripts are on top:
187 $postMscripts = $this->mScripts
;
188 $this->mScripts
= '';
189 foreach( $core_classes as $js_class ){
190 $this->addScriptClass( $js_class );
192 $this->mScripts
.= $postMscripts;
197 * @param string $js_class 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, $wgEnableJS2system;
204 $path = jsScriptLoader
::getJsPathFromClass( $js_class );
205 if( $path !== false ){
206 if( $wgEnableScriptLoader ) {
207 // Register it with the script loader
208 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ) {
209 $this->mScriptLoaderClassList
[] = $js_class;
212 // Source the script directly
213 $path = $wgScriptPath . '/' . $path;
214 $urlAppend = ( $wgDebugJavaScript ) ?
time() : $this->getURIDparam( $js_class );
215 $this->addScript( Html
::linkedScript( "$path?$urlAppend" ) );
217 //merge in language text (if js2 is on and we have loadGM function)
218 if( $wgEnableJS2system ){
219 $inlineMsg = jsScriptLoader
::getLocalizedMsgsFromClass( $js_class );
220 if( $inlineMsg != '' )
221 $this->addScript( Html
::inlineScript( $inlineMsg ));
226 print "could not find: $js_class\n";
227 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
228 return false; // could not find the class
232 * Get the <script> tag which will invoke the script loader
233 * @param $classAry A class array which, if given, overrides $this->mScriptLoaderClassList
235 function getScriptLoaderJs( $classAry = array() ) {
236 global $wgRequest, $wgDebugJavaScript;
237 // If no class array was provided, use mScriptLoaderClassList
238 if( !count( $classAry ) ) {
239 $classAry = $this->mScriptLoaderClassList
;
241 $class_list = implode( ',', $classAry );
243 $debug_param = ( $wgDebugJavaScript ||
244 $wgRequest->getVal( 'debug' ) == 'true' ||
245 $wgRequest->getVal( 'debug' ) == '1' )
246 ?
'&debug=true' : '';
248 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) .
249 "?class={$class_list}{$debug_param}&" . $this->getURIDparam( $classAry) );
253 * Get the unique request ID parameter for the script-loader request
255 function getURIDparam( $classAry = array() ) {
256 global $wgDebugJavaScript, $wgStyleVersion, $IP, $wgScriptModifiedCheck;
257 if( $wgDebugJavaScript ) {
258 return 'urid=' . time();
260 //support single class_name attr
261 if( gettype( $classAry) == 'string' ){
262 $classAry = array( $classAry );
265 foreach( $classAry as $class ) {
266 if( $wgScriptModifiedCheck ) {
267 $js_path = jsScriptLoader
::getJsPathFromClass( $class );
269 $cur_ftime = filemtime ( $IP ."/". $js_path );
270 if( $cur_ftime > $ftime )
274 // Add the latest revision ID if the class set includes a WT (wiki title)
275 if( substr($class, 0, 3) == 'WT:'){
276 $title_str = substr($class, 3);
277 $t = Title
::newFromText( $title_str );
278 if( $t && $t->exists() ) {
279 if( $t->getLatestRevID() > $frev )
280 $frev = $t->getLatestRevID();
284 //build the actual unique request id:
285 $urid = "urid={$wgStyleVersion}";
287 // Add the file modification time if set
289 $urid .= "_" . $ftime;
291 //add the wiki rev id if set
300 * Given a script path, get the JS class name, or false if no such path is registered.
301 * @param $path string
303 function getJsClassFromPath( $path ) {
304 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
306 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
307 foreach( $scriptLoaderPaths as $js_class => $js_path ) {
308 $js_path = "{$wgScriptPath}/{$js_path}";
309 if( $path == $js_path )
316 * Add a self-contained script tag with the given contents
317 * @param string $script JavaScript text, no <script> tags
319 function addInlineScript( $script ) {
320 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
324 * Get all registered JS and CSS tags for the header.
326 function getScript() {
327 global $wgEnableScriptLoader;
328 if( $wgEnableScriptLoader ){
329 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
331 return $this->mScripts
. $this->getHeadItems();
335 function getHeadItems() {
337 foreach ( $this->mHeadItems
as $item ) {
343 function addHeadItem( $name, $value ) {
344 $this->mHeadItems
[$name] = $value;
347 function hasHeadItem( $name ) {
348 return isset( $this->mHeadItems
[$name] );
351 function setETag($tag) { $this->mETag
= $tag; }
352 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
353 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
355 function addLink( $linkarr ) {
356 # $linkarr should be an associative array of attributes. We'll escape on output.
357 array_push( $this->mLinktags
, $linkarr );
360 # Get all links added by extensions
361 function getExtStyle() {
362 return $this->mExtStyles
;
365 function addMetadataLink( $linkarr ) {
366 # note: buggy CC software only reads first "meta" link
367 static $haveMeta = false;
368 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
369 $this->addLink( $linkarr );
374 * checkLastModified tells the client to use the client-cached page if
375 * possible. If sucessful, the OutputPage is disabled so that
376 * any future call to OutputPage->output() have no effect.
378 * Side effect: sets mLastModified for Last-Modified header
380 * @return bool True iff cache-ok headers was sent.
382 function checkLastModified( $timestamp ) {
383 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
385 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
386 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
389 if( !$wgCachePages ) {
390 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
393 if( $wgUser->getOption( 'nocache' ) ) {
394 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
398 $timestamp = wfTimestamp( TS_MW
, $timestamp );
399 $modifiedTimes = array(
400 'page' => $timestamp,
401 'user' => $wgUser->getTouched(),
402 'epoch' => $wgCacheEpoch
404 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
406 $maxModified = max( $modifiedTimes );
407 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
409 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
410 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
416 foreach ( $modifiedTimes as $name => $value ) {
417 if ( $info !== '' ) {
420 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
423 # IE sends sizes after the date like this:
424 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
425 # this breaks strtotime().
426 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
428 wfSuppressWarnings(); // E_STRICT system time bitching
429 $clientHeaderTime = strtotime( $clientHeader );
431 if ( !$clientHeaderTime ) {
432 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
435 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
437 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
438 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
439 wfDebug( __METHOD__
. ": effective Last-Modified: " .
440 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
441 if( $clientHeaderTime < $maxModified ) {
442 wfDebug( __METHOD__
. ": STALE, $info\n", false );
447 # Give a 304 response code and disable body output
448 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
449 ini_set('zlib.output_compression', 0);
450 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
451 $this->sendCacheControl();
454 // Don't output a compressed blob when using ob_gzhandler;
455 // it's technically against HTTP spec and seems to confuse
456 // Firefox when the response gets split over two packets.
457 wfClearOutputBuffers();
462 function setPageTitleActionText( $text ) {
463 $this->mPageTitleActionText
= $text;
466 function getPageTitleActionText () {
467 if ( isset( $this->mPageTitleActionText
) ) {
468 return $this->mPageTitleActionText
;
473 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
475 * @param $policy string The literal string to output as the contents of
476 * the meta tag. Will be parsed according to the spec and output in
480 public function setRobotPolicy( $policy ) {
481 $policy = Article
::formatRobotPolicy( $policy );
483 if( isset( $policy['index'] ) ){
484 $this->setIndexPolicy( $policy['index'] );
486 if( isset( $policy['follow'] ) ){
487 $this->setFollowPolicy( $policy['follow'] );
492 * Set the index policy for the page, but leave the follow policy un-
495 * @param $policy string Either 'index' or 'noindex'.
498 public function setIndexPolicy( $policy ) {
499 $policy = trim( $policy );
500 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
501 $this->mIndexPolicy
= $policy;
506 * Set the follow policy for the page, but leave the index policy un-
509 * @param $policy string Either 'follow' or 'nofollow'.
512 public function setFollowPolicy( $policy ) {
513 $policy = trim( $policy );
514 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
515 $this->mFollowPolicy
= $policy;
520 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
522 public function setHTMLTitle( $name ) {
523 $this->mHTMLtitle
= $name;
527 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
528 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
529 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
530 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
532 public function setPageTitle( $name ) {
534 $name = $wgContLang->convert( $name, true );
535 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
536 # but leave "<i>foobar</i>" alone
537 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
538 $this->mPagetitle
= $nameWithTags;
540 $taction = $this->getPageTitleActionText();
541 if( !empty( $taction ) ) {
542 $name .= ' - '.$taction;
545 # change "<i>foo&bar</i>" to "foo&bar"
546 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
549 public function setTitle( $t ) {
553 public function getTitle() {
554 if ( $this->mTitle
instanceof Title
) {
555 return $this->mTitle
;
558 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
564 public function getHTMLTitle() { return $this->mHTMLtitle
; }
565 public function getPageTitle() { return $this->mPagetitle
; }
566 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
567 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
568 public function getSubtitle() { return $this->mSubtitle
; }
569 public function isArticle() { return $this->mIsarticle
; }
570 public function setPrintable() { $this->mPrintable
= true; }
571 public function isPrintable() { return $this->mPrintable
; }
572 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
573 public function isSyndicated() { return $this->mShowFeedLinks
; }
574 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
575 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
576 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
577 public function getOnloadHandler() { return $this->mOnloadHandler
; }
578 public function disable() { $this->mDoNothing
= true; }
579 public function isDisabled() { return $this->mDoNothing
; }
581 public function setArticleRelated( $v ) {
582 $this->mIsArticleRelated
= $v;
584 $this->mIsarticle
= false;
587 public function setArticleFlag( $v ) {
588 $this->mIsarticle
= $v;
590 $this->mIsArticleRelated
= $v;
594 public function isArticleRelated() { return $this->mIsArticleRelated
; }
596 public function getLanguageLinks() { return $this->mLanguageLinks
; }
597 public function addLanguageLinks($newLinkArray) {
598 $this->mLanguageLinks +
= $newLinkArray;
600 public function setLanguageLinks($newLinkArray) {
601 $this->mLanguageLinks
= $newLinkArray;
604 public function getCategoryLinks() {
605 return $this->mCategoryLinks
;
609 * Add an array of categories, with names in the keys
611 public function addCategoryLinks( $categories ) {
612 global $wgUser, $wgContLang;
614 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
618 # Add the links to a LinkBatch
619 $arr = array( NS_CATEGORY
=> $categories );
621 $lb->setArray( $arr );
623 # Fetch existence plus the hiddencat property
624 $dbr = wfGetDB( DB_SLAVE
);
625 $pageTable = $dbr->tableName( 'page' );
626 $where = $lb->constructSet( 'page', $dbr );
627 $propsTable = $dbr->tableName( 'page_props' );
628 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
629 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
630 $res = $dbr->query( $sql, __METHOD__
);
632 # Add the results to the link cache
633 $lb->addResultToCache( LinkCache
::singleton(), $res );
635 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
636 $categories = array_combine( array_keys( $categories ),
637 array_fill( 0, count( $categories ), 'normal' ) );
639 # Mark hidden categories
640 foreach ( $res as $row ) {
641 if ( isset( $row->pp_value
) ) {
642 $categories[$row->page_title
] = 'hidden';
646 # Add the remaining categories to the skin
647 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
648 $sk = $wgUser->getSkin();
649 foreach ( $categories as $category => $type ) {
650 $origcategory = $category;
651 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
652 $wgContLang->findVariantLink( $category, $title, true );
653 if ( $category != $origcategory )
654 if ( array_key_exists( $category, $categories ) )
656 $text = $wgContLang->convertHtml( $title->getText() );
657 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
662 public function setCategoryLinks($categories) {
663 $this->mCategoryLinks
= array();
664 $this->addCategoryLinks($categories);
667 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
668 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
670 public function disallowUserJs() { $this->mAllowUserJs
= false; }
671 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
673 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
674 public function addHTML( $text ) { $this->mBodytext
.= $text; }
675 public function clearHTML() { $this->mBodytext
= ''; }
676 public function getHTML() { return $this->mBodytext
; }
677 public function debug( $text ) { $this->mDebugtext
.= $text; }
680 public function setParserOptions( $options ) {
681 wfDeprecated( __METHOD__
);
682 return $this->parserOptions( $options );
685 public function parserOptions( $options = null ) {
686 if ( !$this->mParserOptions
) {
687 $this->mParserOptions
= new ParserOptions
;
689 return wfSetVar( $this->mParserOptions
, $options );
693 * Set the revision ID which will be seen by the wiki text parser
694 * for things such as embedded {{REVISIONID}} variable use.
695 * @param mixed $revid an integer, or NULL
696 * @return mixed previous value
698 public function setRevisionId( $revid ) {
699 $val = is_null( $revid ) ?
null : intval( $revid );
700 return wfSetVar( $this->mRevisionId
, $val );
703 public function getRevisionId() {
704 return $this->mRevisionId
;
708 * Convert wikitext to HTML and add it to the buffer
709 * Default assumes that the current page title will
712 * @param string $text
713 * @param bool $linestart
715 public function addWikiText( $text, $linestart = true ) {
716 $title = $this->getTitle(); // Work arround E_STRICT
717 $this->addWikiTextTitle( $text, $title, $linestart );
720 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
721 $this->addWikiTextTitle($text, $title, $linestart);
724 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
725 $this->addWikiTextTitle( $text, $title, $linestart, true );
728 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
731 wfProfileIn( __METHOD__
);
733 wfIncrStats( 'pcache_not_possible' );
735 $popts = $this->parserOptions();
736 $oldTidy = $popts->setTidy( $tidy );
738 $parserOutput = $wgParser->parse( $text, $title, $popts,
739 $linestart, true, $this->mRevisionId
);
741 $popts->setTidy( $oldTidy );
743 $this->addParserOutput( $parserOutput );
745 wfProfileOut( __METHOD__
);
750 * @param ParserOutput object &$parserOutput
752 public function addParserOutputNoText( &$parserOutput ) {
753 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
755 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
756 $this->addCategoryLinks( $parserOutput->getCategories() );
757 $this->mNewSectionLink
= $parserOutput->getNewSection();
758 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
760 $this->mParseWarnings
= $parserOutput->getWarnings();
761 if ( $parserOutput->getCacheTime() == -1 ) {
762 $this->enableClientCache( false );
764 $this->mNoGallery
= $parserOutput->getNoGallery();
765 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
767 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
768 if ( isset( $this->mTemplateIds
[$ns] ) ) {
769 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
771 $this->mTemplateIds
[$ns] = $dbks;
775 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
776 $this->setPageTitle( $dt );
777 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
778 $this->setPageTitle( $title );
780 // Hooks registered in the object
781 global $wgParserOutputHooks;
782 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
783 list( $hookName, $data ) = $hookInfo;
784 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
785 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
789 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
794 * @param ParserOutput &$parserOutput
796 function addParserOutput( &$parserOutput ) {
797 $this->addParserOutputNoText( $parserOutput );
798 $text = $parserOutput->getText();
799 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
800 $this->addHTML( $text );
804 * Add wikitext to the buffer, assuming that this is the primary text for a page view
805 * Saves the text into the parser cache if possible.
807 * @param string $text
808 * @param Article $article
810 * @deprecated Use Article::outputWikitext
812 public function addPrimaryWikiText( $text, $article, $cache = true ) {
815 wfDeprecated( __METHOD__
);
817 $popts = $this->parserOptions();
818 $popts->setTidy(true);
819 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
820 $popts, true, true, $this->mRevisionId
);
821 $popts->setTidy(false);
822 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
823 $parserCache = ParserCache
::singleton();
824 $parserCache->save( $parserOutput, $article, $popts);
827 $this->addParserOutput( $parserOutput );
831 * @deprecated use addWikiTextTidy()
833 public function addSecondaryWikiText( $text, $linestart = true ) {
834 wfDeprecated( __METHOD__
);
835 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
839 * Add wikitext with tidy enabled
841 public function addWikiTextTidy( $text, $linestart = true ) {
842 $title = $this->getTitle();
843 $this->addWikiTextTitleTidy($text, $title, $linestart);
848 * Add the output of a QuickTemplate to the output buffer
850 * @param QuickTemplate $template
852 public function addTemplate( &$template ) {
854 $template->execute();
855 $this->addHTML( ob_get_contents() );
860 * Parse wikitext and return the HTML.
862 * @param string $text
863 * @param bool $linestart Is this the start of a line?
864 * @param bool $interface ??
866 public function parse( $text, $linestart = true, $interface = false ) {
868 if( is_null( $this->getTitle() ) ) {
869 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
871 $popts = $this->parserOptions();
872 if ( $interface) { $popts->setInterfaceMessage(true); }
873 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
874 $linestart, true, $this->mRevisionId
);
875 if ( $interface) { $popts->setInterfaceMessage(false); }
876 return $parserOutput->getText();
879 /** Parse wikitext, strip paragraphs, and return the HTML. */
880 public function parseInline( $text, $linestart = true, $interface = false ) {
881 $parsed = $this->parse( $text, $linestart, $interface );
884 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
892 * @param Article $article
897 * @return bool True if successful, else false.
899 public function tryParserCache( &$article ) {
900 wfDeprecated( __METHOD__
);
901 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
903 if ($parserOutput !== false) {
904 $this->addParserOutput( $parserOutput );
912 * @param int $maxage Maximum cache time on the Squid, in seconds.
914 public function setSquidMaxage( $maxage ) {
915 $this->mSquidMaxage
= $maxage;
919 * Use enableClientCache(false) to force it to send nocache headers
922 public function enableClientCache( $state ) {
923 return wfSetVar( $this->mEnableClientCache
, $state );
926 function getCacheVaryCookies() {
927 global $wgCookiePrefix, $wgCacheVaryCookies;
929 if ( $cookies === null ) {
930 $cookies = array_merge(
932 "{$wgCookiePrefix}Token",
933 "{$wgCookiePrefix}LoggedOut",
938 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
943 function uncacheableBecauseRequestVars() {
945 return $wgRequest->getText('useskin', false) === false
946 && $wgRequest->getText('uselang', false) === false;
950 * Check if the request has a cache-varying cookie header
951 * If it does, it's very important that we don't allow public caching
953 function haveCacheVaryCookies() {
955 $cookieHeader = $wgRequest->getHeader( 'cookie' );
956 if ( $cookieHeader === false ) {
959 $cvCookies = $this->getCacheVaryCookies();
960 foreach ( $cvCookies as $cookieName ) {
961 # Check for a simple string match, like the way squid does it
962 if ( strpos( $cookieHeader, $cookieName ) ) {
963 wfDebug( __METHOD__
.": found $cookieName\n" );
967 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
971 /** Get a complete X-Vary-Options header */
972 public function getXVO() {
973 $cvCookies = $this->getCacheVaryCookies();
974 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
976 foreach ( $cvCookies as $cookieName ) {
982 $xvo .= 'string-contains=' . $cookieName;
987 public function sendCacheControl() {
988 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
990 $response = $wgRequest->response();
991 if ($wgUseETag && $this->mETag
)
992 $response->header("ETag: $this->mETag");
994 # don't serve compressed data to clients who can't handle it
995 # maintain different caches for logged-in users and non-logged in ones
996 $response->header( 'Vary: Accept-Encoding, Cookie' );
999 # Add an X-Vary-Options header for Squid with Wikimedia patches
1000 $response->header( $this->getXVO() );
1003 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1004 if( $wgUseSquid && session_id() == '' &&
1005 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1008 # We'll purge the proxy cache explicitly, but require end user agents
1009 # to revalidate against the proxy on each visit.
1010 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1011 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1012 # start with a shorter timeout for initial testing
1013 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1014 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1015 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1017 # We'll purge the proxy cache for anons explicitly, but require end user agents
1018 # to revalidate against the proxy on each visit.
1019 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1020 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1021 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1022 # start with a shorter timeout for initial testing
1023 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1024 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1027 # We do want clients to cache if they can, but they *must* check for updates
1028 # on revisiting the page.
1029 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1030 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1031 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1033 if($this->mLastModified
) {
1034 $response->header( "Last-Modified: {$this->mLastModified}" );
1037 wfDebug( __METHOD__
. ": no caching **\n", false );
1039 # In general, the absence of a last modified header should be enough to prevent
1040 # the client from using its cache. We send a few other things just to make sure.
1041 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1042 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1043 $response->header( 'Pragma: no-cache' );
1048 * Finally, all the text has been munged and accumulated into
1049 * the object, let's actually output it:
1051 public function output() {
1052 global $wgUser, $wgOutputEncoding, $wgRequest;
1053 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1054 global $wgUseAjax, $wgAjaxWatch;
1055 global $wgEnableMWSuggest, $wgUniversalEditButton;
1058 if( $this->mDoNothing
){
1061 wfProfileIn( __METHOD__
);
1062 if ( '' != $this->mRedirect
) {
1063 # Standards require redirect URLs to be absolute
1064 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1065 if( $this->mRedirectCode
== '301') {
1066 if( !$wgDebugRedirects ) {
1067 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1069 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1071 $this->sendCacheControl();
1073 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1074 if( $wgDebugRedirects ) {
1075 $url = htmlspecialchars( $this->mRedirect
);
1076 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1077 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1078 print "</body>\n</html>\n";
1080 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1082 wfProfileOut( __METHOD__
);
1085 elseif ( $this->mStatusCode
)
1087 $statusMessage = array(
1089 101 => 'Switching Protocols',
1090 102 => 'Processing',
1094 203 => 'Non-Authoritative Information',
1095 204 => 'No Content',
1096 205 => 'Reset Content',
1097 206 => 'Partial Content',
1098 207 => 'Multi-Status',
1099 300 => 'Multiple Choices',
1100 301 => 'Moved Permanently',
1103 304 => 'Not Modified',
1105 307 => 'Temporary Redirect',
1106 400 => 'Bad Request',
1107 401 => 'Unauthorized',
1108 402 => 'Payment Required',
1111 405 => 'Method Not Allowed',
1112 406 => 'Not Acceptable',
1113 407 => 'Proxy Authentication Required',
1114 408 => 'Request Timeout',
1117 411 => 'Length Required',
1118 412 => 'Precondition Failed',
1119 413 => 'Request Entity Too Large',
1120 414 => 'Request-URI Too Large',
1121 415 => 'Unsupported Media Type',
1122 416 => 'Request Range Not Satisfiable',
1123 417 => 'Expectation Failed',
1124 422 => 'Unprocessable Entity',
1126 424 => 'Failed Dependency',
1127 500 => 'Internal Server Error',
1128 501 => 'Not Implemented',
1129 502 => 'Bad Gateway',
1130 503 => 'Service Unavailable',
1131 504 => 'Gateway Timeout',
1132 505 => 'HTTP Version Not Supported',
1133 507 => 'Insufficient Storage'
1136 if ( $statusMessage[$this->mStatusCode
] )
1137 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1140 $sk = $wgUser->getSkin();
1142 // Add our core scripts to output
1143 $this->addCoreScripts2Top();
1146 $this->addScriptFile( 'ajax.js' );
1148 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1150 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1151 $this->addScriptFile( 'ajaxwatch.js' );
1154 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1155 $this->addScriptFile( 'mwsuggest.js' );
1159 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1160 $this->addScriptFile( 'rightclickedit.js' );
1163 global $wgUseAJAXCategories, $wgEnableJS2system;
1164 if ($wgUseAJAXCategories && $wgEnableJS2system) {
1165 global $wgAJAXCategoriesNamespaces;
1167 $title = $this->getTitle();
1169 if( empty( $wgAJAXCategoriesNamespaces ) ||
in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
1170 $this->addScriptClass( 'ajaxCategories' );
1174 if( $wgUniversalEditButton ) {
1175 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1176 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1177 // Original UniversalEditButton
1178 $msg = wfMsg('edit');
1179 $this->addLink( array(
1180 'rel' => 'alternate',
1181 'type' => 'application/x-wiki',
1183 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1185 // Alternate edit link
1186 $this->addLink( array(
1189 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1194 # Buffer output; final headers may depend on later processing
1197 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1198 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1200 if ($this->mArticleBodyOnly
) {
1201 $this->out($this->mBodytext
);
1203 // Hook that allows last minute changes to the output page, e.g.
1204 // adding of CSS or Javascript by extensions.
1205 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1207 wfProfileIn( 'Output-skin' );
1208 $sk->outputPage( $this );
1209 wfProfileOut( 'Output-skin' );
1212 $this->sendCacheControl();
1214 wfProfileOut( __METHOD__
);
1218 * Actually output something with print(). Performs an iconv to the
1219 * output encoding, if needed.
1220 * @param string $ins The string to output
1222 public function out( $ins ) {
1223 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1224 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1227 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1228 if ( false === $outs ) { $outs = $ins; }
1236 public static function setEncodings() {
1237 global $wgInputEncoding, $wgOutputEncoding;
1240 $wgInputEncoding = strtolower( $wgInputEncoding );
1242 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1243 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1246 $wgOutputEncoding = $wgInputEncoding;
1250 * Deprecated, use wfReportTime() instead.
1254 public function reportTime() {
1255 wfDeprecated( __METHOD__
);
1256 $time = wfReportTime();
1261 * Produce a "user is blocked" page.
1263 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1266 function blockedPage( $return = true ) {
1267 global $wgUser, $wgContLang, $wgLang;
1269 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1270 $this->setRobotPolicy( 'noindex,nofollow' );
1271 $this->setArticleRelated( false );
1273 $name = User
::whoIs( $wgUser->blockedBy() );
1274 $reason = $wgUser->blockedFor();
1275 if( $reason == '' ) {
1276 $reason = wfMsg( 'blockednoreason' );
1278 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1281 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1283 $blockid = $wgUser->mBlock
->mId
;
1285 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1286 if ( $blockExpiry == 'infinity' ) {
1287 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1288 // Search for localization in 'ipboptions'
1289 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1290 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1291 if ( strpos( $option, ":" ) === false )
1293 list( $show, $value ) = explode( ":", $option );
1294 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1295 $blockExpiry = $show;
1300 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1303 if ( $wgUser->mBlock
->mAuto
) {
1304 $msg = 'autoblockedtext';
1306 $msg = 'blockedtext';
1309 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1310 * This could be a username, an ip range, or a single ip. */
1311 $intended = $wgUser->mBlock
->mAddress
;
1313 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1315 # Don't auto-return to special pages
1317 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1318 $this->returnToMain( null, $return );
1323 * Output a standard error page
1325 * @param string $title Message key for page title
1326 * @param string $msg Message key for page text
1327 * @param array $params Message parameters
1329 public function showErrorPage( $title, $msg, $params = array() ) {
1330 if ( $this->getTitle() ) {
1331 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1333 $this->setPageTitle( wfMsg( $title ) );
1334 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1335 $this->setRobotPolicy( 'noindex,nofollow' );
1336 $this->setArticleRelated( false );
1337 $this->enableClientCache( false );
1338 $this->mRedirect
= '';
1339 $this->mBodytext
= '';
1341 array_unshift( $params, 'parse' );
1342 array_unshift( $params, $msg );
1343 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1345 $this->returnToMain();
1349 * Output a standard permission error page
1351 * @param array $errors Error message keys
1353 public function showPermissionsErrorPage( $errors, $action = null )
1355 $this->mDebugtext
.= 'Original title: ' .
1356 $this->getTitle()->getPrefixedText() . "\n";
1357 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1358 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1359 $this->setRobotPolicy( 'noindex,nofollow' );
1360 $this->setArticleRelated( false );
1361 $this->enableClientCache( false );
1362 $this->mRedirect
= '';
1363 $this->mBodytext
= '';
1364 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1368 public function errorpage( $title, $msg ) {
1369 wfDeprecated( __METHOD__
);
1370 throw new ErrorPageError( $title, $msg );
1374 * Display an error page indicating that a given version of MediaWiki is
1375 * required to use it
1377 * @param mixed $version The version of MediaWiki needed to use the page
1379 public function versionRequired( $version ) {
1380 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1381 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1382 $this->setRobotPolicy( 'noindex,nofollow' );
1383 $this->setArticleRelated( false );
1384 $this->mBodytext
= '';
1386 $this->addWikiMsg( 'versionrequiredtext', $version );
1387 $this->returnToMain();
1391 * Display an error page noting that a given permission bit is required.
1393 * @param string $permission key required
1395 public function permissionRequired( $permission ) {
1398 $this->setPageTitle( wfMsg( 'badaccess' ) );
1399 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1400 $this->setRobotPolicy( 'noindex,nofollow' );
1401 $this->setArticleRelated( false );
1402 $this->mBodytext
= '';
1404 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1405 User
::getGroupsWithPermission( $permission ) );
1407 $this->addWikiMsg( 'badaccess-groups',
1408 $wgLang->commaList( $groups ),
1411 $this->addWikiMsg( 'badaccess-group0' );
1413 $this->returnToMain();
1417 * Use permissionRequired.
1420 public function sysopRequired() {
1421 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1425 * Use permissionRequired.
1428 public function developerRequired() {
1429 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1433 * Produce the stock "please login to use the wiki" page
1435 public function loginToUse() {
1436 global $wgUser, $wgContLang;
1438 if( $wgUser->isLoggedIn() ) {
1439 $this->permissionRequired( 'read' );
1443 $skin = $wgUser->getSkin();
1445 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1446 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1447 $this->setRobotPolicy( 'noindex,nofollow' );
1448 $this->setArticleFlag( false );
1450 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1451 $loginLink = $skin->link(
1453 wfMsgHtml( 'loginreqlink' ),
1455 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1456 array( 'known', 'noclasses' )
1458 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1459 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1461 # Don't return to the main page if the user can't read it
1462 # otherwise we'll end up in a pointless loop
1463 $mainPage = Title
::newMainPage();
1464 if( $mainPage->userCanRead() )
1465 $this->returnToMain( null, $mainPage );
1469 public function databaseError( $fname, $sql, $error, $errno ) {
1470 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1474 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1475 * @return string The wikitext error-messages, formatted into a list.
1477 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1478 if ($action == null) {
1479 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1482 $action_desc = wfMsgNoTrans( "action-$action" );
1483 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1486 if (count( $errors ) > 1) {
1487 $text .= '<ul class="permissions-errors">' . "\n";
1489 foreach( $errors as $error )
1492 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1497 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1504 * Display a page stating that the Wiki is in read-only mode,
1505 * and optionally show the source of the page that the user
1506 * was trying to edit. Should only be called (for this
1507 * purpose) after wfReadOnly() has returned true.
1509 * For historical reasons, this function is _also_ used to
1510 * show the error message when a user tries to edit a page
1511 * they are not allowed to edit. (Unless it's because they're
1512 * blocked, then we show blockedPage() instead.) In this
1513 * case, the second parameter should be set to true and a list
1514 * of reasons supplied as the third parameter.
1516 * @todo Needs to be split into multiple functions.
1518 * @param string $source Source code to show (or null).
1519 * @param bool $protected Is this a permissions error?
1520 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1522 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1524 $skin = $wgUser->getSkin();
1526 $this->setRobotPolicy( 'noindex,nofollow' );
1527 $this->setArticleRelated( false );
1529 // If no reason is given, just supply a default "I can't let you do
1530 // that, Dave" message. Should only occur if called by legacy code.
1531 if ( $protected && empty($reasons) ) {
1532 $reasons[] = array( 'badaccess-group0' );
1535 if ( !empty($reasons) ) {
1536 // Permissions error
1538 $this->setPageTitle( wfMsg( 'viewsource' ) );
1547 array( 'known', 'noclasses' )
1552 $this->setPageTitle( wfMsg( 'badaccess' ) );
1554 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1556 // Wiki is read only
1557 $this->setPageTitle( wfMsg( 'readonly' ) );
1558 $reason = wfReadOnlyReason();
1559 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1562 // Show source, if supplied
1563 if( is_string( $source ) ) {
1564 $this->addWikiMsg( 'viewsourcetext' );
1565 $text = Xml
::openElement( 'textarea',
1566 array( 'id' => 'wpTextbox1',
1567 'name' => 'wpTextbox1',
1568 'cols' => $wgUser->getOption( 'cols' ),
1569 'rows' => $wgUser->getOption( 'rows' ),
1570 'readonly' => 'readonly' ) );
1571 $text .= htmlspecialchars( $source );
1572 $text .= Xml
::closeElement( 'textarea' );
1573 $this->addHTML( $text );
1575 // Show templates used by this article
1576 $skin = $wgUser->getSkin();
1577 $article = new Article( $this->getTitle() );
1578 $this->addHTML( "<div class='templatesUsed'>
1579 {$skin->formatTemplates( $article->getUsedTemplates() )}
1584 # If the title doesn't exist, it's fairly pointless to print a return
1585 # link to it. After all, you just tried editing it and couldn't, so
1586 # what's there to do there?
1587 if( $this->getTitle()->exists() ) {
1588 $this->returnToMain( null, $this->getTitle() );
1593 public function fatalError( $message ) {
1594 wfDeprecated( __METHOD__
);
1595 throw new FatalError( $message );
1599 public function unexpectedValueError( $name, $val ) {
1600 wfDeprecated( __METHOD__
);
1601 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1605 public function fileCopyError( $old, $new ) {
1606 wfDeprecated( __METHOD__
);
1607 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1611 public function fileRenameError( $old, $new ) {
1612 wfDeprecated( __METHOD__
);
1613 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1617 public function fileDeleteError( $name ) {
1618 wfDeprecated( __METHOD__
);
1619 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1623 public function fileNotFoundError( $name ) {
1624 wfDeprecated( __METHOD__
);
1625 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1628 public function showFatalError( $message ) {
1629 $this->setPageTitle( wfMsg( "internalerror" ) );
1630 $this->setRobotPolicy( "noindex,nofollow" );
1631 $this->setArticleRelated( false );
1632 $this->enableClientCache( false );
1633 $this->mRedirect
= '';
1634 $this->mBodytext
= $message;
1637 public function showUnexpectedValueError( $name, $val ) {
1638 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1641 public function showFileCopyError( $old, $new ) {
1642 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1645 public function showFileRenameError( $old, $new ) {
1646 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1649 public function showFileDeleteError( $name ) {
1650 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1653 public function showFileNotFoundError( $name ) {
1654 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1658 * Add a "return to" link pointing to a specified title
1660 * @param Title $title Title to link
1661 * @param string $query Query string
1663 public function addReturnTo( $title, $query = array() ) {
1665 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1666 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1667 $title, null, array(), $query ) );
1668 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1672 * Add a "return to" link pointing to a specified title,
1673 * or the title indicated in the request, or else the main page
1675 * @param null $unused No longer used
1676 * @param Title $returnto Title to return to
1678 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1681 if ( $returnto == null ) {
1682 $returnto = $wgRequest->getText( 'returnto' );
1685 if ( $returntoquery == null ) {
1686 $returntoquery = $wgRequest->getText( 'returntoquery' );
1689 if ( '' === $returnto ) {
1690 $returnto = Title
::newMainPage();
1693 if ( is_object( $returnto ) ) {
1694 $titleObj = $returnto;
1696 $titleObj = Title
::newFromText( $returnto );
1698 if ( !is_object( $titleObj ) ) {
1699 $titleObj = Title
::newMainPage();
1702 $this->addReturnTo( $titleObj, $returntoquery );
1706 * @return string The doctype, opening <html>, and head element.
1708 * @param $sk Skin The given Skin
1710 public function headElement( Skin
$sk , $includeStyle = true ) {
1711 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1712 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1713 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1715 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1716 if ( $sk->commonPrintStylesheet() ) {
1717 $this->addStyle( 'common/wikiprintable.css', 'print' );
1719 $sk->setupUserCss( $this );
1723 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1724 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1727 if ( '' == $this->getHTMLTitle() ) {
1728 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1731 $dir = $wgContLang->getDir();
1734 $ret .= "<!doctype html>\n";
1735 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1737 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1738 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1739 foreach($wgXhtmlNamespaces as $tag => $ns) {
1740 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1742 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1746 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1747 $ret .= implode( "\n", array(
1748 $this->getHeadLinks(),
1749 $this->buildCssLinks(),
1750 $sk->getHeadScripts( $this ),
1751 $this->getHeadItems(),
1754 $ret .= Html
::inlineStyle( $sk->usercss
);
1757 if( $wgEnableScriptLoader )
1758 $ret .= $this->getScriptLoaderJs();
1760 if ($wgUseTrackbacks && $this->isArticleRelated())
1761 $ret .= $this->getTitle()->trackbackRDF();
1763 $ret .= "</head>\n";
1767 protected function addDefaultMeta() {
1768 global $wgVersion, $wgHtml5;
1770 static $called = false;
1772 # Don't run this twice
1778 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1780 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1782 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1783 if( $p !== 'index,follow' ) {
1784 // http://www.robotstxt.org/wc/meta-user.html
1785 // Only show if it's different from the default robots policy
1786 $this->addMeta( 'robots', $p );
1789 if ( count( $this->mKeywords
) > 0 ) {
1791 "/<.*?" . ">/" => '',
1794 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1799 * @return string HTML tag links to be put in the header.
1801 public function getHeadLinks() {
1802 global $wgRequest, $wgFeed;
1804 // Ideally this should happen earlier, somewhere. :P
1805 $this->addDefaultMeta();
1809 foreach ( $this->mMetatags
as $tag ) {
1810 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1812 $tag[0] = substr( $tag[0], 5 );
1816 $tags[] = Xml
::element( 'meta',
1819 'content' => $tag[1] ) );
1821 foreach ( $this->mLinktags
as $tag ) {
1822 $tags[] = Xml
::element( 'link', $tag );
1826 foreach( $this->getSyndicationLinks() as $format => $link ) {
1827 # Use the page name for the title (accessed through $wgTitle since
1828 # there's no other way). In principle, this could lead to issues
1829 # with having the same name for different feeds corresponding to
1830 # the same page, but we can't avoid that at this low a level.
1832 $tags[] = $this->feedLink(
1835 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1838 # Recent changes feed should appear on every page (except recentchanges,
1839 # that would be redundant). Put it after the per-page feed to avoid
1840 # changing existing behavior. It's still available, probably via a
1841 # menu in your browser. Some sites might have a different feed they'd
1842 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1843 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1844 # If so, use it instead.
1846 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1847 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1849 if ( $wgOverrideSiteFeed ) {
1850 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1851 $tags[] = $this->feedLink (
1853 htmlspecialchars( $feedUrl ),
1854 wfMsg( "site-{$type}-feed", $wgSitename ) );
1857 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1858 foreach( $wgFeedClasses as $format => $class ) {
1859 $tags[] = $this->feedLink(
1861 $rctitle->getLocalURL( "feed={$format}" ),
1862 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1867 return implode( "\n", $tags ) . "\n";
1871 * Return URLs for each supported syndication format for this page.
1872 * @return array associating format keys with URLs
1874 public function getSyndicationLinks() {
1875 global $wgFeedClasses;
1878 if( $this->isSyndicated() ) {
1879 if( is_string( $this->getFeedAppendQuery() ) ) {
1880 $appendQuery = "&" . $this->getFeedAppendQuery();
1885 foreach( $wgFeedClasses as $format => $class ) {
1886 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1893 * Generate a <link rel/> for an RSS feed.
1895 private function feedLink( $type, $url, $text ) {
1896 return Xml
::element( 'link', array(
1897 'rel' => 'alternate',
1898 'type' => "application/$type+xml",
1904 * Add a local or specified stylesheet, with the given media options.
1905 * Meant primarily for internal use...
1907 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1908 * @param $conditional -- for IE conditional comments, specifying an IE version
1909 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1911 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1913 // Even though we expect the media type to be lowercase, but here we
1914 // force it to lowercase to be safe.
1916 $options['media'] = $media;
1918 $options['condition'] = $condition;
1920 $options['dir'] = $dir;
1921 $this->styles
[$style] = $options;
1925 * Adds inline CSS styles
1926 * @param $style_css Mixed: inline CSS
1928 public function addInlineStyle( $style_css ){
1929 $this->mScripts
.= Html
::inlineStyle( $style_css );
1933 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1934 * These will be applied to various media & IE conditionals.
1936 public function buildCssLinks() {
1938 foreach( $this->styles
as $file => $options ) {
1939 $link = $this->styleLink( $file, $options );
1944 return implode( "\n", $links );
1947 protected function styleLink( $style, $options ) {
1950 if( isset( $options['dir'] ) ) {
1952 $siteDir = $wgContLang->getDir();
1953 if( $siteDir != $options['dir'] )
1957 if( isset( $options['media'] ) ) {
1958 $media = $this->transformCssMedia( $options['media'] );
1959 if( is_null( $media ) ) {
1966 if( substr( $style, 0, 1 ) == '/' ||
1967 substr( $style, 0, 5 ) == 'http:' ||
1968 substr( $style, 0, 6 ) == 'https:' ) {
1971 global $wgStylePath, $wgStyleVersion;
1972 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1975 $link = Html
::linkedStyle( $url, $media );
1977 if( isset( $options['condition'] ) ) {
1978 $condition = htmlspecialchars( $options['condition'] );
1979 $link = "<!--[if $condition]>$link<![endif]-->";
1984 function transformCssMedia( $media ) {
1985 global $wgRequest, $wgHandheldForIPhone;
1987 // Switch in on-screen display for media testing
1989 'printable' => 'print',
1990 'handheld' => 'handheld',
1992 foreach( $switches as $switch => $targetMedia ) {
1993 if( $wgRequest->getBool( $switch ) ) {
1994 if( $media == $targetMedia ) {
1996 } elseif( $media == 'screen' ) {
2002 // Expand longer media queries as iPhone doesn't grok 'handheld'
2003 if( $wgHandheldForIPhone ) {
2004 $mediaAliases = array(
2005 'screen' => 'screen and (min-device-width: 481px)',
2006 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2009 if( isset( $mediaAliases[$media] ) ) {
2010 $media = $mediaAliases[$media];
2018 * Turn off regular page output and return an error reponse
2019 * for when rate limiting has triggered.
2021 public function rateLimited() {
2023 $this->setPageTitle(wfMsg('actionthrottled'));
2024 $this->setRobotPolicy( 'noindex,follow' );
2025 $this->setArticleRelated( false );
2026 $this->enableClientCache( false );
2027 $this->mRedirect
= '';
2029 $this->setStatusCode(503);
2030 $this->addWikiMsg( 'actionthrottledtext' );
2032 $this->returnToMain( null, $this->getTitle() );
2036 * Show an "add new section" link?
2040 public function showNewSectionLink() {
2041 return $this->mNewSectionLink
;
2045 * Forcibly hide the new section link?
2049 public function forceHideNewSectionLink() {
2050 return $this->mHideNewSectionLink
;
2054 * Show a warning about slave lag
2056 * If the lag is higher than $wgSlaveLagCritical seconds,
2057 * then the warning is a bit more obvious. If the lag is
2058 * lower than $wgSlaveLagWarning, then no warning is shown.
2060 * @param int $lag Slave lag
2062 public function showLagWarning( $lag ) {
2063 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2064 if( $lag >= $wgSlaveLagWarning ) {
2065 $message = $lag < $wgSlaveLagCritical
2068 $warning = wfMsgExt( $message, 'parse', $lag );
2069 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2074 * Add a wikitext-formatted message to the output.
2075 * This is equivalent to:
2077 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2079 public function addWikiMsg( /*...*/ ) {
2080 $args = func_get_args();
2081 $name = array_shift( $args );
2082 $this->addWikiMsgArray( $name, $args );
2086 * Add a wikitext-formatted message to the output.
2087 * Like addWikiMsg() except the parameters are taken as an array
2088 * instead of a variable argument list.
2090 * $options is passed through to wfMsgExt(), see that function for details.
2092 public function addWikiMsgArray( $name, $args, $options = array() ) {
2093 $options[] = 'parse';
2094 $text = wfMsgExt( $name, $options, $args );
2095 $this->addHTML( $text );
2099 * This function takes a number of message/argument specifications, wraps them in
2100 * some overall structure, and then parses the result and adds it to the output.
2102 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2103 * on. The subsequent arguments may either be strings, in which case they are the
2104 * message names, or arrays, in which case the first element is the message name,
2105 * and subsequent elements are the parameters to that message.
2107 * The special named parameter 'options' in a message specification array is passed
2108 * through to the $options parameter of wfMsgExt().
2110 * Don't use this for messages that are not in users interface language.
2114 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2118 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2120 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2121 $msgSpecs = func_get_args();
2122 array_shift( $msgSpecs );
2123 $msgSpecs = array_values( $msgSpecs );
2125 foreach ( $msgSpecs as $n => $spec ) {
2127 if ( is_array( $spec ) ) {
2129 $name = array_shift( $args );
2130 if ( isset( $args['options'] ) ) {
2131 $options = $args['options'];
2132 unset( $args['options'] );
2138 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2140 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );