3adb63bb920d48662c03101ef1e83d77182f13be
2 if ( ! defined( 'MEDIAWIKI' ) )
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mLanguageLinks = array();
17 var $mScriptLoaderClassList = array();
18 // the most recent id of any script that is grouped in the script request
19 var $mLatestScriptRevID = 0;
21 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
22 var $mTemplateIds = array();
25 var $mSuppressQuickbar = false;
26 var $mOnloadHandler = '';
27 var $mDoNothing = false;
28 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
29 var $mIsArticleRelated = true;
30 protected $mParserOptions = null; // lazy initialised, use parserOptions()
31 var $mShowFeedLinks = false;
32 var $mFeedLinksAppendQuery = false;
33 var $mEnableClientCache = true;
34 var $mArticleBodyOnly = false;
36 var $mNewSectionLink = false;
37 var $mHideNewSectionLink = false;
38 var $mNoGallery = false;
39 var $mPageTitleActionText = '';
40 var $mParseWarnings = array();
41 var $mSquidMaxage = 0;
42 var $mRevisionId = null;
43 protected $mTitle = null;
46 * An array of stylesheet filenames (relative from skins path), with options
47 * for CSS media, IE conditions, and RTL/LTR direction.
48 * For internal use; add settings in the skin via $this->addStyle()
50 var $styles = array();
52 private $mIndexPolicy = 'index';
53 private $mFollowPolicy = 'follow';
57 * Initialise private variables
59 function __construct() {
60 global $wgAllowUserJs;
61 $this->mAllowUserJs
= $wgAllowUserJs;
64 public function redirect( $url, $responsecode = '302' ) {
65 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
66 $this->mRedirect
= str_replace( "\n", '', $url );
67 $this->mRedirectCode
= $responsecode;
70 public function getRedirect() {
71 return $this->mRedirect
;
75 * Set the HTTP status code to send with the output.
77 * @param int $statusCode
80 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
83 * Add a new <meta> tag
84 * To add an http-equiv meta tag, precede the name with "http:"
86 * @param $name tag name
87 * @param $val tag value
89 function addMeta( $name, $val ) {
90 array_push( $this->mMetatags
, array( $name, $val ) );
93 function addKeyword( $text ) {
94 if( is_array( $text )) {
95 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
97 array_push( $this->mKeywords
, $text );
100 function addScript( $script ) {
101 $this->mScripts
.= $script . "\n";
105 * Register and add a stylesheet from an extension directory.
106 * @param $url String path to sheet. Provide either a full url (beginning
107 * with 'http', etc) or a relative path from the document root
108 * (beginning with '/'). Otherwise it behaves identically to
109 * addStyle() and draws from the /skins folder.
111 public function addExtensionStyle( $url ) {
112 array_push( $this->mExtStyles
, $url );
116 * Add a JavaScript file out of skins/common, or a given relative path.
117 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
119 function addScriptFile( $file ) {
120 global $wgStylePath, $wgScript, $wgUser;
121 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
123 if( substr( $file, 0, 1 ) == '/' ) {
126 $path = "{$wgStylePath}/common/{$file}";
129 if( $wgEnableScriptLoader ){
130 if( strpos( $path, $wgScript ) !== false ){
131 $reqPath = str_replace( $wgScript . '?', '', $path );
132 $reqArgs = explode( '&', $reqPath );
135 foreach( $reqArgs as $arg ){
136 list( $key, $var ) = explode( '=', $arg );
137 $reqSet[$key] = $var;
140 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
141 // extract any extra param (for now just skin)
142 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' ) ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
143 $this->mScriptLoaderClassList
[] = 'WT:' . $reqSet['title'] . $ext_param ;
144 // add the title revision to the key
145 $t = Title
::newFromText( $reqSet['title'] );
146 // if there is no title (don't worry we just use the $wgStyleVersion var (which should be updated on relevant commits)
147 if( $t && $t->exists() ){
148 if( $t->getLatestRevID() > $this->mLatestScriptRevID
)
149 $this->mLatestScriptRevID
= $t->getLatestRevID();
155 // check for class from path:
156 $js_class = $this->getJsClassFromPath( $path );
158 // add to the class list:
159 $this->mScriptLoaderClassList
[] = $js_class;
164 // if the script loader did not find a way to add the script than add using addScript
165 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
169 * This is the core script that is included on every page
170 * (they are requested separately to improve caching across
171 * different page load types (edit, upload, view, etc)
173 function addCoreScripts2Top(){
174 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgEnableJS2system;
175 //@@todo we should deprecate wikibits in favor of mv_embed and native jQuery functions
177 if( $wgEnableJS2system ){
178 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
180 $core_classes = array( 'wikibits' );
183 if( $wgEnableScriptLoader ){
184 $this->mScripts
= $this->getScriptLoaderJs( $core_classes ) . $this->mScripts
;
187 foreach( $core_classes as $s ){
188 if( isset( $wgJSAutoloadLocalClasses[$s] ) ){
189 $so .= Html
::linkedScript( "{$wgScriptPath}/{$wgJSAutoloadLocalClasses[$s]}?" . $this->getURIDparam() );
192 $this->mScripts
= $so . $this->mScripts
;
197 * @param $js_class String: name of JavaScript class
198 * @return Boolean: false if class wasn't found, true on success
200 function addScriptClass( $js_class ){
201 global $wgDebugJavaScript, $wgJSAutoloadLocalClasses, $wgJSAutoloadClasses,
202 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath;
204 if( isset( $wgJSAutoloadClasses[$js_class] ) ||
isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
205 if( $wgEnableScriptLoader ){
206 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ){
207 $this->mScriptLoaderClassList
[] = $js_class;
210 // do a normal load of without the script-loader:
211 $path = $wgScriptPath . '/';
212 if( isset( $wgJSAutoloadClasses[$js_class] ) ){
213 $path.= $wgJSAutoloadClasses[$js_class];
214 }else if( isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
215 $path.= $wgJSAutoloadLocalClasses[$js_class];
217 $urlAppend = ( $wgDebugJavaScript ) ?
time() : $wgStyleVersion;
218 $this->addScript( Html
::linkedScript( "$path?$urlAppend" ) );
222 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
223 return false; // could not find the class
227 * gets the scriptLoader javascript include
228 * @param $forcClassAry Boolean: false by default
230 function getScriptLoaderJs( $forceClassAry = false ){
231 global $wgRequest, $wgDebugJavaScript;
233 if( !$forceClassAry ){
234 $class_list = implode( ',', $this->mScriptLoaderClassList
);
236 $class_list = implode( ',', $forceClassAry );
239 $debug_param = ( $wgDebugJavaScript ||
240 $wgRequest->getVal( 'debug' ) == 'true' ||
241 $wgRequest->getVal( 'debug' ) == '1' )
242 ?
'&debug=true' : '';
244 //@@todo intelligent unique id generation based on svn version of file (rather than just grabbing the $wgStyleVersion var)
245 //@@todo we should check the packaged message text in this javascript file for updates and update the $mScriptLoaderURID id (in getJsClassFromPath)
247 //generate the unique request param (combine with the most recent revision id of any wiki page with the $wgStyleVersion var)
249 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) . "?class={$class_list}{$debug_param}&" . $this->getURIDparam() );
252 function getURIDparam(){
253 global $wgDebugJavaScript, $wgStyleVersion;
254 if( $wgDebugJavaScript ){
255 return 'urid=' . time();
257 return "urid={$wgStyleVersion}_{$this->mLatestScriptRevID}";
261 function getJsClassFromPath( $path ){
262 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
264 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
265 foreach( $scriptLoaderPaths as $js_class => $js_path ){
266 $js_path = "{$wgScriptPath}/{$js_path}";
267 if( $path == $js_path )
274 * Add a self-contained script tag with the given contents
275 * @param string $script JavaScript text, no <script> tags
277 function addInlineScript( $script ) {
278 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
281 function getScript() {
282 global $wgEnableScriptLoader;
283 if( $wgEnableScriptLoader ){
284 //include $this->mScripts (for anything that we could not package into the scriptloader
285 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
287 return $this->mScripts
. $this->getHeadItems();
291 function getHeadItems() {
293 foreach ( $this->mHeadItems
as $item ) {
299 function addHeadItem( $name, $value ) {
300 $this->mHeadItems
[$name] = $value;
303 function hasHeadItem( $name ) {
304 return isset( $this->mHeadItems
[$name] );
307 function setETag($tag) { $this->mETag
= $tag; }
308 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
309 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
311 function addLink( $linkarr ) {
312 # $linkarr should be an associative array of attributes. We'll escape on output.
313 array_push( $this->mLinktags
, $linkarr );
316 # Get all links added by extensions
317 function getExtStyle() {
318 return $this->mExtStyles
;
321 function addMetadataLink( $linkarr ) {
322 # note: buggy CC software only reads first "meta" link
323 static $haveMeta = false;
324 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
325 $this->addLink( $linkarr );
330 * checkLastModified tells the client to use the client-cached page if
331 * possible. If sucessful, the OutputPage is disabled so that
332 * any future call to OutputPage->output() have no effect.
334 * Side effect: sets mLastModified for Last-Modified header
336 * @return bool True iff cache-ok headers was sent.
338 function checkLastModified( $timestamp ) {
339 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
341 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
342 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
345 if( !$wgCachePages ) {
346 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
349 if( $wgUser->getOption( 'nocache' ) ) {
350 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
354 $timestamp = wfTimestamp( TS_MW
, $timestamp );
355 $modifiedTimes = array(
356 'page' => $timestamp,
357 'user' => $wgUser->getTouched(),
358 'epoch' => $wgCacheEpoch
360 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
362 $maxModified = max( $modifiedTimes );
363 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
365 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
366 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
372 foreach ( $modifiedTimes as $name => $value ) {
373 if ( $info !== '' ) {
376 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
379 # IE sends sizes after the date like this:
380 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
381 # this breaks strtotime().
382 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
384 wfSuppressWarnings(); // E_STRICT system time bitching
385 $clientHeaderTime = strtotime( $clientHeader );
387 if ( !$clientHeaderTime ) {
388 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
391 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
393 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
394 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
395 wfDebug( __METHOD__
. ": effective Last-Modified: " .
396 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
397 if( $clientHeaderTime < $maxModified ) {
398 wfDebug( __METHOD__
. ": STALE, $info\n", false );
403 # Give a 304 response code and disable body output
404 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
405 ini_set('zlib.output_compression', 0);
406 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
407 $this->sendCacheControl();
410 // Don't output a compressed blob when using ob_gzhandler;
411 // it's technically against HTTP spec and seems to confuse
412 // Firefox when the response gets split over two packets.
413 wfClearOutputBuffers();
418 function setPageTitleActionText( $text ) {
419 $this->mPageTitleActionText
= $text;
422 function getPageTitleActionText () {
423 if ( isset( $this->mPageTitleActionText
) ) {
424 return $this->mPageTitleActionText
;
429 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
431 * @param $policy string The literal string to output as the contents of
432 * the meta tag. Will be parsed according to the spec and output in
436 public function setRobotPolicy( $policy ) {
437 $policy = Article
::formatRobotPolicy( $policy );
439 if( isset( $policy['index'] ) ){
440 $this->setIndexPolicy( $policy['index'] );
442 if( isset( $policy['follow'] ) ){
443 $this->setFollowPolicy( $policy['follow'] );
448 * Set the index policy for the page, but leave the follow policy un-
451 * @param $policy string Either 'index' or 'noindex'.
454 public function setIndexPolicy( $policy ) {
455 $policy = trim( $policy );
456 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
457 $this->mIndexPolicy
= $policy;
462 * Set the follow policy for the page, but leave the index policy un-
465 * @param $policy string Either 'follow' or 'nofollow'.
468 public function setFollowPolicy( $policy ) {
469 $policy = trim( $policy );
470 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
471 $this->mFollowPolicy
= $policy;
476 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
478 public function setHTMLTitle( $name ) {
479 $this->mHTMLtitle
= $name;
483 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
484 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
485 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
486 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
488 public function setPageTitle( $name ) {
490 $name = $wgContLang->convert( $name, true );
491 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
492 # but leave "<i>foobar</i>" alone
493 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
494 $this->mPagetitle
= $nameWithTags;
496 $taction = $this->getPageTitleActionText();
497 if( !empty( $taction ) ) {
498 $name .= ' - '.$taction;
501 # change "<i>foo&bar</i>" to "foo&bar"
502 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
505 public function setTitle( $t ) {
509 public function getTitle() {
510 if ( $this->mTitle
instanceof Title
) {
511 return $this->mTitle
;
514 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
520 public function getHTMLTitle() { return $this->mHTMLtitle
; }
521 public function getPageTitle() { return $this->mPagetitle
; }
522 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
523 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
524 public function getSubtitle() { return $this->mSubtitle
; }
525 public function isArticle() { return $this->mIsarticle
; }
526 public function setPrintable() { $this->mPrintable
= true; }
527 public function isPrintable() { return $this->mPrintable
; }
528 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
529 public function isSyndicated() { return $this->mShowFeedLinks
; }
530 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
531 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
532 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
533 public function getOnloadHandler() { return $this->mOnloadHandler
; }
534 public function disable() { $this->mDoNothing
= true; }
535 public function isDisabled() { return $this->mDoNothing
; }
537 public function setArticleRelated( $v ) {
538 $this->mIsArticleRelated
= $v;
540 $this->mIsarticle
= false;
543 public function setArticleFlag( $v ) {
544 $this->mIsarticle
= $v;
546 $this->mIsArticleRelated
= $v;
550 public function isArticleRelated() { return $this->mIsArticleRelated
; }
552 public function getLanguageLinks() { return $this->mLanguageLinks
; }
553 public function addLanguageLinks($newLinkArray) {
554 $this->mLanguageLinks +
= $newLinkArray;
556 public function setLanguageLinks($newLinkArray) {
557 $this->mLanguageLinks
= $newLinkArray;
560 public function getCategoryLinks() {
561 return $this->mCategoryLinks
;
565 * Add an array of categories, with names in the keys
567 public function addCategoryLinks( $categories ) {
568 global $wgUser, $wgContLang;
570 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
574 # Add the links to a LinkBatch
575 $arr = array( NS_CATEGORY
=> $categories );
577 $lb->setArray( $arr );
579 # Fetch existence plus the hiddencat property
580 $dbr = wfGetDB( DB_SLAVE
);
581 $pageTable = $dbr->tableName( 'page' );
582 $where = $lb->constructSet( 'page', $dbr );
583 $propsTable = $dbr->tableName( 'page_props' );
584 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
585 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
586 $res = $dbr->query( $sql, __METHOD__
);
588 # Add the results to the link cache
589 $lb->addResultToCache( LinkCache
::singleton(), $res );
591 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
592 $categories = array_combine( array_keys( $categories ),
593 array_fill( 0, count( $categories ), 'normal' ) );
595 # Mark hidden categories
596 foreach ( $res as $row ) {
597 if ( isset( $row->pp_value
) ) {
598 $categories[$row->page_title
] = 'hidden';
602 # Add the remaining categories to the skin
603 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
604 $sk = $wgUser->getSkin();
605 foreach ( $categories as $category => $type ) {
606 $origcategory = $category;
607 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
608 $wgContLang->findVariantLink( $category, $title, true );
609 if ( $category != $origcategory )
610 if ( array_key_exists( $category, $categories ) )
612 $text = $wgContLang->convertHtml( $title->getText() );
613 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
618 public function setCategoryLinks($categories) {
619 $this->mCategoryLinks
= array();
620 $this->addCategoryLinks($categories);
623 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
624 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
626 public function disallowUserJs() { $this->mAllowUserJs
= false; }
627 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
629 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
630 public function addHTML( $text ) { $this->mBodytext
.= $text; }
631 public function clearHTML() { $this->mBodytext
= ''; }
632 public function getHTML() { return $this->mBodytext
; }
633 public function debug( $text ) { $this->mDebugtext
.= $text; }
636 public function setParserOptions( $options ) {
637 wfDeprecated( __METHOD__
);
638 return $this->parserOptions( $options );
641 public function parserOptions( $options = null ) {
642 if ( !$this->mParserOptions
) {
643 $this->mParserOptions
= new ParserOptions
;
645 return wfSetVar( $this->mParserOptions
, $options );
649 * Set the revision ID which will be seen by the wiki text parser
650 * for things such as embedded {{REVISIONID}} variable use.
651 * @param mixed $revid an integer, or NULL
652 * @return mixed previous value
654 public function setRevisionId( $revid ) {
655 $val = is_null( $revid ) ?
null : intval( $revid );
656 return wfSetVar( $this->mRevisionId
, $val );
659 public function getRevisionId() {
660 return $this->mRevisionId
;
664 * Convert wikitext to HTML and add it to the buffer
665 * Default assumes that the current page title will
668 * @param string $text
669 * @param bool $linestart
671 public function addWikiText( $text, $linestart = true ) {
672 $title = $this->getTitle(); // Work arround E_STRICT
673 $this->addWikiTextTitle( $text, $title, $linestart );
676 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
677 $this->addWikiTextTitle($text, $title, $linestart);
680 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
681 $this->addWikiTextTitle( $text, $title, $linestart, true );
684 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
687 wfProfileIn( __METHOD__
);
689 wfIncrStats( 'pcache_not_possible' );
691 $popts = $this->parserOptions();
692 $oldTidy = $popts->setTidy( $tidy );
694 $parserOutput = $wgParser->parse( $text, $title, $popts,
695 $linestart, true, $this->mRevisionId
);
697 $popts->setTidy( $oldTidy );
699 $this->addParserOutput( $parserOutput );
701 wfProfileOut( __METHOD__
);
706 * @param ParserOutput object &$parserOutput
708 public function addParserOutputNoText( &$parserOutput ) {
709 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
711 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
712 $this->addCategoryLinks( $parserOutput->getCategories() );
713 $this->mNewSectionLink
= $parserOutput->getNewSection();
714 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
716 $this->mParseWarnings
= $parserOutput->getWarnings();
717 if ( $parserOutput->getCacheTime() == -1 ) {
718 $this->enableClientCache( false );
720 $this->mNoGallery
= $parserOutput->getNoGallery();
721 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
723 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
724 if ( isset( $this->mTemplateIds
[$ns] ) ) {
725 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
727 $this->mTemplateIds
[$ns] = $dbks;
731 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
732 $this->setPageTitle( $dt );
733 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
734 $this->setPageTitle( $title );
736 // Hooks registered in the object
737 global $wgParserOutputHooks;
738 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
739 list( $hookName, $data ) = $hookInfo;
740 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
741 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
745 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
750 * @param ParserOutput &$parserOutput
752 function addParserOutput( &$parserOutput ) {
753 $this->addParserOutputNoText( $parserOutput );
754 $text = $parserOutput->getText();
755 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
756 $this->addHTML( $text );
760 * Add wikitext to the buffer, assuming that this is the primary text for a page view
761 * Saves the text into the parser cache if possible.
763 * @param string $text
764 * @param Article $article
766 * @deprecated Use Article::outputWikitext
768 public function addPrimaryWikiText( $text, $article, $cache = true ) {
771 wfDeprecated( __METHOD__
);
773 $popts = $this->parserOptions();
774 $popts->setTidy(true);
775 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
776 $popts, true, true, $this->mRevisionId
);
777 $popts->setTidy(false);
778 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
779 $parserCache = ParserCache
::singleton();
780 $parserCache->save( $parserOutput, $article, $popts);
783 $this->addParserOutput( $parserOutput );
787 * @deprecated use addWikiTextTidy()
789 public function addSecondaryWikiText( $text, $linestart = true ) {
790 wfDeprecated( __METHOD__
);
791 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
795 * Add wikitext with tidy enabled
797 public function addWikiTextTidy( $text, $linestart = true ) {
798 $title = $this->getTitle();
799 $this->addWikiTextTitleTidy($text, $title, $linestart);
804 * Add the output of a QuickTemplate to the output buffer
806 * @param QuickTemplate $template
808 public function addTemplate( &$template ) {
810 $template->execute();
811 $this->addHTML( ob_get_contents() );
816 * Parse wikitext and return the HTML.
818 * @param string $text
819 * @param bool $linestart Is this the start of a line?
820 * @param bool $interface ??
822 public function parse( $text, $linestart = true, $interface = false ) {
824 if( is_null( $this->getTitle() ) ) {
825 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
827 $popts = $this->parserOptions();
828 if ( $interface) { $popts->setInterfaceMessage(true); }
829 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
830 $linestart, true, $this->mRevisionId
);
831 if ( $interface) { $popts->setInterfaceMessage(false); }
832 return $parserOutput->getText();
835 /** Parse wikitext, strip paragraphs, and return the HTML. */
836 public function parseInline( $text, $linestart = true, $interface = false ) {
837 $parsed = $this->parse( $text, $linestart, $interface );
840 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
848 * @param Article $article
853 * @return bool True if successful, else false.
855 public function tryParserCache( &$article ) {
856 wfDeprecated( __METHOD__
);
857 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
859 if ($parserOutput !== false) {
860 $this->addParserOutput( $parserOutput );
868 * @param int $maxage Maximum cache time on the Squid, in seconds.
870 public function setSquidMaxage( $maxage ) {
871 $this->mSquidMaxage
= $maxage;
875 * Use enableClientCache(false) to force it to send nocache headers
878 public function enableClientCache( $state ) {
879 return wfSetVar( $this->mEnableClientCache
, $state );
882 function getCacheVaryCookies() {
883 global $wgCookiePrefix, $wgCacheVaryCookies;
885 if ( $cookies === null ) {
886 $cookies = array_merge(
888 "{$wgCookiePrefix}Token",
889 "{$wgCookiePrefix}LoggedOut",
894 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
899 function uncacheableBecauseRequestVars() {
901 return $wgRequest->getText('useskin', false) === false
902 && $wgRequest->getText('uselang', false) === false;
906 * Check if the request has a cache-varying cookie header
907 * If it does, it's very important that we don't allow public caching
909 function haveCacheVaryCookies() {
911 $cookieHeader = $wgRequest->getHeader( 'cookie' );
912 if ( $cookieHeader === false ) {
915 $cvCookies = $this->getCacheVaryCookies();
916 foreach ( $cvCookies as $cookieName ) {
917 # Check for a simple string match, like the way squid does it
918 if ( strpos( $cookieHeader, $cookieName ) ) {
919 wfDebug( __METHOD__
.": found $cookieName\n" );
923 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
927 /** Get a complete X-Vary-Options header */
928 public function getXVO() {
929 $cvCookies = $this->getCacheVaryCookies();
930 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
932 foreach ( $cvCookies as $cookieName ) {
938 $xvo .= 'string-contains=' . $cookieName;
943 public function sendCacheControl() {
944 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
946 $response = $wgRequest->response();
947 if ($wgUseETag && $this->mETag
)
948 $response->header("ETag: $this->mETag");
950 # don't serve compressed data to clients who can't handle it
951 # maintain different caches for logged-in users and non-logged in ones
952 $response->header( 'Vary: Accept-Encoding, Cookie' );
955 # Add an X-Vary-Options header for Squid with Wikimedia patches
956 $response->header( $this->getXVO() );
959 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
960 if( $wgUseSquid && session_id() == '' &&
961 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
964 # We'll purge the proxy cache explicitly, but require end user agents
965 # to revalidate against the proxy on each visit.
966 # Surrogate-Control controls our Squid, Cache-Control downstream caches
967 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
968 # start with a shorter timeout for initial testing
969 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
970 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
971 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
973 # We'll purge the proxy cache for anons explicitly, but require end user agents
974 # to revalidate against the proxy on each visit.
975 # IMPORTANT! The Squid needs to replace the Cache-Control header with
976 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
977 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
978 # start with a shorter timeout for initial testing
979 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
980 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
983 # We do want clients to cache if they can, but they *must* check for updates
984 # on revisiting the page.
985 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
986 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
987 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
989 if($this->mLastModified
) {
990 $response->header( "Last-Modified: {$this->mLastModified}" );
993 wfDebug( __METHOD__
. ": no caching **\n", false );
995 # In general, the absence of a last modified header should be enough to prevent
996 # the client from using its cache. We send a few other things just to make sure.
997 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
998 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
999 $response->header( 'Pragma: no-cache' );
1004 * Finally, all the text has been munged and accumulated into
1005 * the object, let's actually output it:
1007 public function output() {
1008 global $wgUser, $wgOutputEncoding, $wgRequest;
1009 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1010 global $wgUseAjax, $wgAjaxWatch;
1011 global $wgEnableMWSuggest, $wgUniversalEditButton;
1014 if( $this->mDoNothing
){
1017 wfProfileIn( __METHOD__
);
1018 if ( '' != $this->mRedirect
) {
1019 # Standards require redirect URLs to be absolute
1020 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1021 if( $this->mRedirectCode
== '301') {
1022 if( !$wgDebugRedirects ) {
1023 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1025 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1027 $this->sendCacheControl();
1029 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1030 if( $wgDebugRedirects ) {
1031 $url = htmlspecialchars( $this->mRedirect
);
1032 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1033 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1034 print "</body>\n</html>\n";
1036 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1038 wfProfileOut( __METHOD__
);
1041 elseif ( $this->mStatusCode
)
1043 $statusMessage = array(
1045 101 => 'Switching Protocols',
1046 102 => 'Processing',
1050 203 => 'Non-Authoritative Information',
1051 204 => 'No Content',
1052 205 => 'Reset Content',
1053 206 => 'Partial Content',
1054 207 => 'Multi-Status',
1055 300 => 'Multiple Choices',
1056 301 => 'Moved Permanently',
1059 304 => 'Not Modified',
1061 307 => 'Temporary Redirect',
1062 400 => 'Bad Request',
1063 401 => 'Unauthorized',
1064 402 => 'Payment Required',
1067 405 => 'Method Not Allowed',
1068 406 => 'Not Acceptable',
1069 407 => 'Proxy Authentication Required',
1070 408 => 'Request Timeout',
1073 411 => 'Length Required',
1074 412 => 'Precondition Failed',
1075 413 => 'Request Entity Too Large',
1076 414 => 'Request-URI Too Large',
1077 415 => 'Unsupported Media Type',
1078 416 => 'Request Range Not Satisfiable',
1079 417 => 'Expectation Failed',
1080 422 => 'Unprocessable Entity',
1082 424 => 'Failed Dependency',
1083 500 => 'Internal Server Error',
1084 501 => 'Not Implemented',
1085 502 => 'Bad Gateway',
1086 503 => 'Service Unavailable',
1087 504 => 'Gateway Timeout',
1088 505 => 'HTTP Version Not Supported',
1089 507 => 'Insufficient Storage'
1092 if ( $statusMessage[$this->mStatusCode
] )
1093 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1096 $sk = $wgUser->getSkin();
1098 // add our core scripts to output
1099 $this->addCoreScripts2Top();
1102 $this->addScriptFile( 'ajax.js' );
1104 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1106 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1107 $this->addScriptFile( 'ajaxwatch.js' );
1110 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1111 $this->addScriptFile( 'mwsuggest.js' );
1115 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1116 $this->addScriptFile( 'rightclickedit.js' );
1119 if( $wgUniversalEditButton ) {
1120 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1121 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1122 // Original UniversalEditButton
1123 $msg = wfMsg('edit');
1124 $this->addLink( array(
1125 'rel' => 'alternate',
1126 'type' => 'application/x-wiki',
1128 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1130 // Alternate edit link
1131 $this->addLink( array(
1134 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1139 # Buffer output; final headers may depend on later processing
1142 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1143 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1145 if ($this->mArticleBodyOnly
) {
1146 $this->out($this->mBodytext
);
1148 // Hook that allows last minute changes to the output page, e.g.
1149 // adding of CSS or Javascript by extensions.
1150 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1152 wfProfileIn( 'Output-skin' );
1153 $sk->outputPage( $this );
1154 wfProfileOut( 'Output-skin' );
1157 $this->sendCacheControl();
1159 wfProfileOut( __METHOD__
);
1163 * Actually output something with print(). Performs an iconv to the
1164 * output encoding, if needed.
1165 * @param string $ins The string to output
1167 public function out( $ins ) {
1168 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1169 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1172 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1173 if ( false === $outs ) { $outs = $ins; }
1181 public static function setEncodings() {
1182 global $wgInputEncoding, $wgOutputEncoding;
1185 $wgInputEncoding = strtolower( $wgInputEncoding );
1187 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1188 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1191 $wgOutputEncoding = $wgInputEncoding;
1195 * Deprecated, use wfReportTime() instead.
1199 public function reportTime() {
1200 wfDeprecated( __METHOD__
);
1201 $time = wfReportTime();
1206 * Produce a "user is blocked" page.
1208 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1211 function blockedPage( $return = true ) {
1212 global $wgUser, $wgContLang, $wgLang;
1214 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1215 $this->setRobotPolicy( 'noindex,nofollow' );
1216 $this->setArticleRelated( false );
1218 $name = User
::whoIs( $wgUser->blockedBy() );
1219 $reason = $wgUser->blockedFor();
1220 if( $reason == '' ) {
1221 $reason = wfMsg( 'blockednoreason' );
1223 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1226 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1228 $blockid = $wgUser->mBlock
->mId
;
1230 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1231 if ( $blockExpiry == 'infinity' ) {
1232 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1233 // Search for localization in 'ipboptions'
1234 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1235 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1236 if ( strpos( $option, ":" ) === false )
1238 list( $show, $value ) = explode( ":", $option );
1239 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1240 $blockExpiry = $show;
1245 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1248 if ( $wgUser->mBlock
->mAuto
) {
1249 $msg = 'autoblockedtext';
1251 $msg = 'blockedtext';
1254 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1255 * This could be a username, an ip range, or a single ip. */
1256 $intended = $wgUser->mBlock
->mAddress
;
1258 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1260 # Don't auto-return to special pages
1262 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1263 $this->returnToMain( null, $return );
1268 * Output a standard error page
1270 * @param string $title Message key for page title
1271 * @param string $msg Message key for page text
1272 * @param array $params Message parameters
1274 public function showErrorPage( $title, $msg, $params = array() ) {
1275 if ( $this->getTitle() ) {
1276 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1278 $this->setPageTitle( wfMsg( $title ) );
1279 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1280 $this->setRobotPolicy( 'noindex,nofollow' );
1281 $this->setArticleRelated( false );
1282 $this->enableClientCache( false );
1283 $this->mRedirect
= '';
1284 $this->mBodytext
= '';
1286 array_unshift( $params, 'parse' );
1287 array_unshift( $params, $msg );
1288 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1290 $this->returnToMain();
1294 * Output a standard permission error page
1296 * @param array $errors Error message keys
1298 public function showPermissionsErrorPage( $errors, $action = null )
1300 $this->mDebugtext
.= 'Original title: ' .
1301 $this->getTitle()->getPrefixedText() . "\n";
1302 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1303 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1304 $this->setRobotPolicy( 'noindex,nofollow' );
1305 $this->setArticleRelated( false );
1306 $this->enableClientCache( false );
1307 $this->mRedirect
= '';
1308 $this->mBodytext
= '';
1309 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1313 public function errorpage( $title, $msg ) {
1314 wfDeprecated( __METHOD__
);
1315 throw new ErrorPageError( $title, $msg );
1319 * Display an error page indicating that a given version of MediaWiki is
1320 * required to use it
1322 * @param mixed $version The version of MediaWiki needed to use the page
1324 public function versionRequired( $version ) {
1325 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1326 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1327 $this->setRobotPolicy( 'noindex,nofollow' );
1328 $this->setArticleRelated( false );
1329 $this->mBodytext
= '';
1331 $this->addWikiMsg( 'versionrequiredtext', $version );
1332 $this->returnToMain();
1336 * Display an error page noting that a given permission bit is required.
1338 * @param string $permission key required
1340 public function permissionRequired( $permission ) {
1343 $this->setPageTitle( wfMsg( 'badaccess' ) );
1344 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1345 $this->setRobotPolicy( 'noindex,nofollow' );
1346 $this->setArticleRelated( false );
1347 $this->mBodytext
= '';
1349 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1350 User
::getGroupsWithPermission( $permission ) );
1352 $this->addWikiMsg( 'badaccess-groups',
1353 $wgLang->commaList( $groups ),
1356 $this->addWikiMsg( 'badaccess-group0' );
1358 $this->returnToMain();
1362 * Use permissionRequired.
1365 public function sysopRequired() {
1366 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1370 * Use permissionRequired.
1373 public function developerRequired() {
1374 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1378 * Produce the stock "please login to use the wiki" page
1380 public function loginToUse() {
1381 global $wgUser, $wgContLang;
1383 if( $wgUser->isLoggedIn() ) {
1384 $this->permissionRequired( 'read' );
1388 $skin = $wgUser->getSkin();
1390 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1391 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1392 $this->setRobotPolicy( 'noindex,nofollow' );
1393 $this->setArticleFlag( false );
1395 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1396 $loginLink = $skin->link(
1398 wfMsgHtml( 'loginreqlink' ),
1400 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1401 array( 'known', 'noclasses' )
1403 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1404 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1406 # Don't return to the main page if the user can't read it
1407 # otherwise we'll end up in a pointless loop
1408 $mainPage = Title
::newMainPage();
1409 if( $mainPage->userCanRead() )
1410 $this->returnToMain( null, $mainPage );
1414 public function databaseError( $fname, $sql, $error, $errno ) {
1415 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1419 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1420 * @return string The wikitext error-messages, formatted into a list.
1422 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1423 if ($action == null) {
1424 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1427 $action_desc = wfMsgNoTrans( "action-$action" );
1428 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1431 if (count( $errors ) > 1) {
1432 $text .= '<ul class="permissions-errors">' . "\n";
1434 foreach( $errors as $error )
1437 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1442 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1449 * Display a page stating that the Wiki is in read-only mode,
1450 * and optionally show the source of the page that the user
1451 * was trying to edit. Should only be called (for this
1452 * purpose) after wfReadOnly() has returned true.
1454 * For historical reasons, this function is _also_ used to
1455 * show the error message when a user tries to edit a page
1456 * they are not allowed to edit. (Unless it's because they're
1457 * blocked, then we show blockedPage() instead.) In this
1458 * case, the second parameter should be set to true and a list
1459 * of reasons supplied as the third parameter.
1461 * @todo Needs to be split into multiple functions.
1463 * @param string $source Source code to show (or null).
1464 * @param bool $protected Is this a permissions error?
1465 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1467 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1469 $skin = $wgUser->getSkin();
1471 $this->setRobotPolicy( 'noindex,nofollow' );
1472 $this->setArticleRelated( false );
1474 // If no reason is given, just supply a default "I can't let you do
1475 // that, Dave" message. Should only occur if called by legacy code.
1476 if ( $protected && empty($reasons) ) {
1477 $reasons[] = array( 'badaccess-group0' );
1480 if ( !empty($reasons) ) {
1481 // Permissions error
1483 $this->setPageTitle( wfMsg( 'viewsource' ) );
1492 array( 'known', 'noclasses' )
1497 $this->setPageTitle( wfMsg( 'badaccess' ) );
1499 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1501 // Wiki is read only
1502 $this->setPageTitle( wfMsg( 'readonly' ) );
1503 $reason = wfReadOnlyReason();
1504 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1507 // Show source, if supplied
1508 if( is_string( $source ) ) {
1509 $this->addWikiMsg( 'viewsourcetext' );
1510 $text = Xml
::openElement( 'textarea',
1511 array( 'id' => 'wpTextbox1',
1512 'name' => 'wpTextbox1',
1513 'cols' => $wgUser->getOption( 'cols' ),
1514 'rows' => $wgUser->getOption( 'rows' ),
1515 'readonly' => 'readonly' ) );
1516 $text .= htmlspecialchars( $source );
1517 $text .= Xml
::closeElement( 'textarea' );
1518 $this->addHTML( $text );
1520 // Show templates used by this article
1521 $skin = $wgUser->getSkin();
1522 $article = new Article( $this->getTitle() );
1523 $this->addHTML( "<div class='templatesUsed'>
1524 {$skin->formatTemplates( $article->getUsedTemplates() )}
1529 # If the title doesn't exist, it's fairly pointless to print a return
1530 # link to it. After all, you just tried editing it and couldn't, so
1531 # what's there to do there?
1532 if( $this->getTitle()->exists() ) {
1533 $this->returnToMain( null, $this->getTitle() );
1538 public function fatalError( $message ) {
1539 wfDeprecated( __METHOD__
);
1540 throw new FatalError( $message );
1544 public function unexpectedValueError( $name, $val ) {
1545 wfDeprecated( __METHOD__
);
1546 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1550 public function fileCopyError( $old, $new ) {
1551 wfDeprecated( __METHOD__
);
1552 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1556 public function fileRenameError( $old, $new ) {
1557 wfDeprecated( __METHOD__
);
1558 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1562 public function fileDeleteError( $name ) {
1563 wfDeprecated( __METHOD__
);
1564 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1568 public function fileNotFoundError( $name ) {
1569 wfDeprecated( __METHOD__
);
1570 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1573 public function showFatalError( $message ) {
1574 $this->setPageTitle( wfMsg( "internalerror" ) );
1575 $this->setRobotPolicy( "noindex,nofollow" );
1576 $this->setArticleRelated( false );
1577 $this->enableClientCache( false );
1578 $this->mRedirect
= '';
1579 $this->mBodytext
= $message;
1582 public function showUnexpectedValueError( $name, $val ) {
1583 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1586 public function showFileCopyError( $old, $new ) {
1587 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1590 public function showFileRenameError( $old, $new ) {
1591 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1594 public function showFileDeleteError( $name ) {
1595 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1598 public function showFileNotFoundError( $name ) {
1599 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1603 * Add a "return to" link pointing to a specified title
1605 * @param Title $title Title to link
1606 * @param string $query Query string
1608 public function addReturnTo( $title, $query = array() ) {
1610 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1611 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1612 $title, null, array(), $query ) );
1613 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1617 * Add a "return to" link pointing to a specified title,
1618 * or the title indicated in the request, or else the main page
1620 * @param null $unused No longer used
1621 * @param Title $returnto Title to return to
1623 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1626 if ( $returnto == null ) {
1627 $returnto = $wgRequest->getText( 'returnto' );
1630 if ( $returntoquery == null ) {
1631 $returntoquery = $wgRequest->getText( 'returntoquery' );
1634 if ( '' === $returnto ) {
1635 $returnto = Title
::newMainPage();
1638 if ( is_object( $returnto ) ) {
1639 $titleObj = $returnto;
1641 $titleObj = Title
::newFromText( $returnto );
1643 if ( !is_object( $titleObj ) ) {
1644 $titleObj = Title
::newMainPage();
1647 $this->addReturnTo( $titleObj, $returntoquery );
1651 * @return string The doctype, opening <html>, and head element.
1653 public function headElement( Skin
$sk ) {
1654 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1655 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1656 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1658 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1659 if ( $sk->commonPrintStylesheet() ) {
1660 $this->addStyle( 'common/wikiprintable.css', 'print' );
1662 $sk->setupUserCss( $this );
1666 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1667 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1670 if ( '' == $this->getHTMLTitle() ) {
1671 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1674 $dir = $wgContLang->getDir();
1677 $ret .= "<!doctype html>\n";
1678 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1680 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1681 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1682 foreach($wgXhtmlNamespaces as $tag => $ns) {
1683 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1685 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1689 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1690 $ret .= implode( "\n", array(
1691 $this->getHeadLinks(),
1692 $this->buildCssLinks(),
1693 $sk->getHeadScripts( $this ),
1694 $this->getHeadItems(),
1697 $ret .= Html
::inlineStyle( $sk->usercss
);
1700 if( $wgEnableScriptLoader )
1701 $ret .= $this->getScriptLoaderJs();
1703 if ($wgUseTrackbacks && $this->isArticleRelated())
1704 $ret .= $this->getTitle()->trackbackRDF();
1706 $ret .= "</head>\n";
1710 protected function addDefaultMeta() {
1711 global $wgVersion, $wgHtml5;
1713 static $called = false;
1715 # Don't run this twice
1721 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1723 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1725 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1726 if( $p !== 'index,follow' ) {
1727 // http://www.robotstxt.org/wc/meta-user.html
1728 // Only show if it's different from the default robots policy
1729 $this->addMeta( 'robots', $p );
1732 if ( count( $this->mKeywords
) > 0 ) {
1734 "/<.*?" . ">/" => '',
1737 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1742 * @return string HTML tag links to be put in the header.
1744 public function getHeadLinks() {
1745 global $wgRequest, $wgFeed;
1747 // Ideally this should happen earlier, somewhere. :P
1748 $this->addDefaultMeta();
1752 foreach ( $this->mMetatags
as $tag ) {
1753 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1755 $tag[0] = substr( $tag[0], 5 );
1759 $tags[] = Xml
::element( 'meta',
1762 'content' => $tag[1] ) );
1764 foreach ( $this->mLinktags
as $tag ) {
1765 $tags[] = Xml
::element( 'link', $tag );
1769 foreach( $this->getSyndicationLinks() as $format => $link ) {
1770 # Use the page name for the title (accessed through $wgTitle since
1771 # there's no other way). In principle, this could lead to issues
1772 # with having the same name for different feeds corresponding to
1773 # the same page, but we can't avoid that at this low a level.
1775 $tags[] = $this->feedLink(
1778 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1781 # Recent changes feed should appear on every page (except recentchanges,
1782 # that would be redundant). Put it after the per-page feed to avoid
1783 # changing existing behavior. It's still available, probably via a
1784 # menu in your browser. Some sites might have a different feed they'd
1785 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1786 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1787 # If so, use it instead.
1789 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1790 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1792 if ( $wgOverrideSiteFeed ) {
1793 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1794 $tags[] = $this->feedLink (
1796 htmlspecialchars( $feedUrl ),
1797 wfMsg( "site-{$type}-feed", $wgSitename ) );
1800 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1801 foreach( $wgFeedClasses as $format => $class ) {
1802 $tags[] = $this->feedLink(
1804 $rctitle->getLocalURL( "feed={$format}" ),
1805 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1810 return implode( "\n", $tags ) . "\n";
1814 * Return URLs for each supported syndication format for this page.
1815 * @return array associating format keys with URLs
1817 public function getSyndicationLinks() {
1818 global $wgFeedClasses;
1821 if( $this->isSyndicated() ) {
1822 if( is_string( $this->getFeedAppendQuery() ) ) {
1823 $appendQuery = "&" . $this->getFeedAppendQuery();
1828 foreach( $wgFeedClasses as $format => $class ) {
1829 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1836 * Generate a <link rel/> for an RSS feed.
1838 private function feedLink( $type, $url, $text ) {
1839 return Xml
::element( 'link', array(
1840 'rel' => 'alternate',
1841 'type' => "application/$type+xml",
1847 * Add a local or specified stylesheet, with the given media options.
1848 * Meant primarily for internal use...
1850 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1851 * @param $conditional -- for IE conditional comments, specifying an IE version
1852 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1854 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1856 // Even though we expect the media type to be lowercase, but here we
1857 // force it to lowercase to be safe.
1859 $options['media'] = $media;
1861 $options['condition'] = $condition;
1863 $options['dir'] = $dir;
1864 $this->styles
[$style] = $options;
1868 * Adds inline CSS styles
1869 * @param $style_css Mixed: inline CSS
1871 public function addInlineStyle( $style_css ){
1872 $this->mScripts
.= Html
::inlineStyle( $style_css );
1876 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1877 * These will be applied to various media & IE conditionals.
1879 public function buildCssLinks() {
1881 foreach( $this->styles
as $file => $options ) {
1882 $link = $this->styleLink( $file, $options );
1887 return implode( "\n", $links );
1890 protected function styleLink( $style, $options ) {
1893 if( isset( $options['dir'] ) ) {
1895 $siteDir = $wgContLang->getDir();
1896 if( $siteDir != $options['dir'] )
1900 if( isset( $options['media'] ) ) {
1901 $media = $this->transformCssMedia( $options['media'] );
1902 if( is_null( $media ) ) {
1909 if( substr( $style, 0, 1 ) == '/' ||
1910 substr( $style, 0, 5 ) == 'http:' ||
1911 substr( $style, 0, 6 ) == 'https:' ) {
1914 global $wgStylePath, $wgStyleVersion;
1915 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1918 $link = Html
::linkedStyle( $url, $media );
1920 if( isset( $options['condition'] ) ) {
1921 $condition = htmlspecialchars( $options['condition'] );
1922 $link = "<!--[if $condition]>$link<![endif]-->";
1927 function transformCssMedia( $media ) {
1928 global $wgRequest, $wgHandheldForIPhone;
1930 // Switch in on-screen display for media testing
1932 'printable' => 'print',
1933 'handheld' => 'handheld',
1935 foreach( $switches as $switch => $targetMedia ) {
1936 if( $wgRequest->getBool( $switch ) ) {
1937 if( $media == $targetMedia ) {
1939 } elseif( $media == 'screen' ) {
1945 // Expand longer media queries as iPhone doesn't grok 'handheld'
1946 if( $wgHandheldForIPhone ) {
1947 $mediaAliases = array(
1948 'screen' => 'screen and (min-device-width: 481px)',
1949 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1952 if( isset( $mediaAliases[$media] ) ) {
1953 $media = $mediaAliases[$media];
1961 * Turn off regular page output and return an error reponse
1962 * for when rate limiting has triggered.
1964 public function rateLimited() {
1966 $this->setPageTitle(wfMsg('actionthrottled'));
1967 $this->setRobotPolicy( 'noindex,follow' );
1968 $this->setArticleRelated( false );
1969 $this->enableClientCache( false );
1970 $this->mRedirect
= '';
1972 $this->setStatusCode(503);
1973 $this->addWikiMsg( 'actionthrottledtext' );
1975 $this->returnToMain( null, $this->getTitle() );
1979 * Show an "add new section" link?
1983 public function showNewSectionLink() {
1984 return $this->mNewSectionLink
;
1988 * Forcibly hide the new section link?
1992 public function forceHideNewSectionLink() {
1993 return $this->mHideNewSectionLink
;
1997 * Show a warning about slave lag
1999 * If the lag is higher than $wgSlaveLagCritical seconds,
2000 * then the warning is a bit more obvious. If the lag is
2001 * lower than $wgSlaveLagWarning, then no warning is shown.
2003 * @param int $lag Slave lag
2005 public function showLagWarning( $lag ) {
2006 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2007 if( $lag >= $wgSlaveLagWarning ) {
2008 $message = $lag < $wgSlaveLagCritical
2011 $warning = wfMsgExt( $message, 'parse', $lag );
2012 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2017 * Add a wikitext-formatted message to the output.
2018 * This is equivalent to:
2020 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2022 public function addWikiMsg( /*...*/ ) {
2023 $args = func_get_args();
2024 $name = array_shift( $args );
2025 $this->addWikiMsgArray( $name, $args );
2029 * Add a wikitext-formatted message to the output.
2030 * Like addWikiMsg() except the parameters are taken as an array
2031 * instead of a variable argument list.
2033 * $options is passed through to wfMsgExt(), see that function for details.
2035 public function addWikiMsgArray( $name, $args, $options = array() ) {
2036 $options[] = 'parse';
2037 $text = wfMsgExt( $name, $options, $args );
2038 $this->addHTML( $text );
2042 * This function takes a number of message/argument specifications, wraps them in
2043 * some overall structure, and then parses the result and adds it to the output.
2045 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2046 * on. The subsequent arguments may either be strings, in which case they are the
2047 * message names, or arrays, in which case the first element is the message name,
2048 * and subsequent elements are the parameters to that message.
2050 * The special named parameter 'options' in a message specification array is passed
2051 * through to the $options parameter of wfMsgExt().
2053 * Don't use this for messages that are not in users interface language.
2057 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2061 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2063 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2064 $msgSpecs = func_get_args();
2065 array_shift( $msgSpecs );
2066 $msgSpecs = array_values( $msgSpecs );
2068 foreach ( $msgSpecs as $n => $spec ) {
2070 if ( is_array( $spec ) ) {
2072 $name = array_shift( $args );
2073 if ( isset( $args['options'] ) ) {
2074 $options = $args['options'];
2075 unset( $args['options'] );
2081 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2083 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );