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 ) { $this->mScripts
.= "\t\t" . $script . "\n"; }
103 * Register and add a stylesheet from an extension directory.
104 * @param $url String path to sheet. Provide either a full url (beginning
105 * with 'http', etc) or a relative path from the document root
106 * (beginning with '/'). Otherwise it behaves identically to
107 * addStyle() and draws from the /skins folder.
109 public function addExtensionStyle( $url ) {
110 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
111 array_push( $this->mExtStyles
, $linkarr );
115 * Add a JavaScript file out of skins/common, or a given relative path.
116 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
118 function addScriptFile( $file ) {
119 global $wgStylePath, $wgStyleVersion, $wgJsMimeType, $wgScript, $wgUser;
120 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
122 if( substr( $file, 0, 1 ) == '/' ) {
125 $path = "{$wgStylePath}/common/{$file}";
128 if( $wgEnableScriptLoader ){
129 if( strpos( $path, $wgScript ) !== false ){
130 $reqPath = str_replace( $wgScript . '?', '', $path );
131 $reqArgs = explode( '&', $reqPath );
134 foreach( $reqArgs as $arg ){
135 list( $key, $var ) = explode( '=', $arg );
136 $reqSet[$key] = $var;
139 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
140 // extract any extra param (for now just skin)
141 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' ) ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
142 $this->mScriptLoaderClassList
[] = 'WT:' . $reqSet['title'] . $ext_param ;
143 // add the title revision to the key
144 $t = Title
::newFromText( $reqSet['title'] );
145 // if there is no title (don't worry we just use the $wgStyleVersion var (which should be updated on relevant commits)
147 if( $t->getLatestRevID() > $this->mLatestScriptRevID
)
148 $this->mLatestScriptRevID
= $t->getLatestRevID();
154 // check for class from path:
155 $js_class = $this->getJsClassFromPath( $path );
157 // add to the class list:
158 $this->mScriptLoaderClassList
[] = $js_class;
163 // if the script loader did not find a way to add the script than add using addScript
165 Xml
::element( 'script',
167 'type' => $wgJsMimeType,
168 'src' => wfAppendQuery( $path, $this->getURIDparam() ),
176 * This is the core script that is included on every page
177 * (they are requested separately to improve caching across
178 * different page load types (edit, upload, view, etc)
180 function addCoreScripts2Top(){
181 global $wgEnableScriptLoader, $wgStyleVersion, $wgJSAutoloadLocalClasses, $wgJsMimeType, $wgScriptPath, $wgEnableJS2system;
182 //@@todo we should deprecate wikibits in favor of mv_embed and native jQuery functions
184 if( $wgEnableJS2system ){
185 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
187 $core_classes = array( 'wikibits' );
190 if( $wgEnableScriptLoader ){
191 $this->mScripts
= $this->getScriptLoaderJs( $core_classes ) . $this->mScripts
;
194 foreach( $core_classes as $s ){
195 if( isset( $wgJSAutoloadLocalClasses[$s] ) ){
196 $so.= Xml
::element( 'script', array(
197 'type' => $wgJsMimeType,
198 'src' => "{$wgScriptPath}/{$wgJSAutoloadLocalClasses[$s]}?" . $this->getURIDparam()
204 $this->mScripts
= $so . $this->mScripts
;
209 * @param $js_class String: name of JavaScript class
210 * @return Boolean: false if class wasn't found, true on success
212 function addScriptClass( $js_class ){
213 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgJsMimeType,
214 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath;
216 if( isset( $wgJSAutoloadClasses[$js_class] ) ||
isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
217 if( $wgEnableScriptLoader ){
218 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ){
219 $this->mScriptLoaderClassList
[] = $js_class;
222 // do a normal load of without the script-loader:
223 $path = $wgScriptPath . '/';
224 $path.= isset( $wgJSAutoloadClasses[$js_class] ) ?
$wgJSAutoloadClasses[$js_class]:
225 $wgJSAutoloadLocalClasses[$js_class];
227 Xml
::element( 'script',
229 'type' => $wgJsMimeType,
230 'src' => "$path?$wgStyleVersion",
238 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
239 return false; // could not find the class
243 * gets the scriptLoader javascript include
244 * @param $forcClassAry Boolean: false by default
246 function getScriptLoaderJs( $forceClassAry = false ){
247 global $wgScriptPath, $wgJsMimeType, $wgStyleVersion, $wgRequest, $wgDebugJavaScript;
249 if( !$forceClassAry ){
250 $class_list = implode( ',', $this->mScriptLoaderClassList
);
252 $class_list = implode( ',', $forceClassAry );
255 $debug_param = ( $wgDebugJavaScript ||
256 $wgRequest->getVal( 'debug' ) == 'true' ||
257 $wgRequest->getVal( 'debug' ) == '1' )
258 ?
'&debug=true' : '';
260 //@@todo intelligent unique id generation based on svn version of file (rather than just grabbing the $wgStyleVersion var)
261 //@@todo we should check the packaged message text in this javascript file for updates and update the $mScriptLoaderURID id (in getJsClassFromPath)
263 //generate the unique request param (combine with the most recent revision id of any wiki page with the $wgStyleVersion var)
266 return Xml
::element( 'script',
268 'type' => $wgJsMimeType,
269 'src' => "$wgScriptPath/mwScriptLoader.php?class={$class_list}{$debug_param}&".$this->getURIDparam(),
275 function getURIDparam(){
276 global $wgDebugJavaScript, $wgStyleVersion;
277 if( $wgDebugJavaScript ){
278 return 'urid=' . time();
280 return "urid={$wgStyleVersion}_{$this->mLatestScriptRevID}";
284 function getJsClassFromPath( $path ){
285 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
287 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
288 foreach( $scriptLoaderPaths as $js_class => $js_path ){
289 $js_path = "{$wgScriptPath}/{$js_path}";
290 if( $path == $js_path )
297 * Add a self-contained script tag with the given contents
298 * @param string $script JavaScript text, no <script> tags
300 function addInlineScript( $script ) {
301 global $wgJsMimeType;
302 $this->mScripts
.= "\t\t<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n\t\t$script\n\t\t/*]]>*/</script>\n";
305 function getScript() {
306 global $wgEnableScriptLoader;
307 if( $wgEnableScriptLoader ){
308 //include $this->mScripts (for anything that we could not package into the scriptloader
309 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
311 return $this->mScripts
. $this->getHeadItems();
315 function getHeadItems() {
317 foreach ( $this->mHeadItems
as $item ) {
323 function addHeadItem( $name, $value ) {
324 $this->mHeadItems
[$name] = $value;
327 function hasHeadItem( $name ) {
328 return isset( $this->mHeadItems
[$name] );
331 function setETag($tag) { $this->mETag
= $tag; }
332 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
333 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly
; }
335 function addLink( $linkarr ) {
336 # $linkarr should be an associative array of attributes. We'll escape on output.
337 array_push( $this->mLinktags
, $linkarr );
340 # Get all links added by extensions
341 function getExtStyle() {
342 return $this->mExtStyles
;
345 function addMetadataLink( $linkarr ) {
346 # note: buggy CC software only reads first "meta" link
347 static $haveMeta = false;
348 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
349 $this->addLink( $linkarr );
354 * checkLastModified tells the client to use the client-cached page if
355 * possible. If sucessful, the OutputPage is disabled so that
356 * any future call to OutputPage->output() have no effect.
358 * Side effect: sets mLastModified for Last-Modified header
360 * @return bool True iff cache-ok headers was sent.
362 function checkLastModified( $timestamp ) {
363 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
365 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
366 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
369 if( !$wgCachePages ) {
370 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
373 if( $wgUser->getOption( 'nocache' ) ) {
374 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
378 $timestamp = wfTimestamp( TS_MW
, $timestamp );
379 $modifiedTimes = array(
380 'page' => $timestamp,
381 'user' => $wgUser->getTouched(),
382 'epoch' => $wgCacheEpoch
384 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
386 $maxModified = max( $modifiedTimes );
387 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
389 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
390 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
396 foreach ( $modifiedTimes as $name => $value ) {
397 if ( $info !== '' ) {
400 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
403 # IE sends sizes after the date like this:
404 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
405 # this breaks strtotime().
406 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
408 wfSuppressWarnings(); // E_STRICT system time bitching
409 $clientHeaderTime = strtotime( $clientHeader );
411 if ( !$clientHeaderTime ) {
412 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
415 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
417 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
418 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
419 wfDebug( __METHOD__
. ": effective Last-Modified: " .
420 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
421 if( $clientHeaderTime < $maxModified ) {
422 wfDebug( __METHOD__
. ": STALE, $info\n", false );
427 # Give a 304 response code and disable body output
428 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
429 ini_set('zlib.output_compression', 0);
430 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
431 $this->sendCacheControl();
434 // Don't output a compressed blob when using ob_gzhandler;
435 // it's technically against HTTP spec and seems to confuse
436 // Firefox when the response gets split over two packets.
437 wfClearOutputBuffers();
442 function setPageTitleActionText( $text ) {
443 $this->mPageTitleActionText
= $text;
446 function getPageTitleActionText () {
447 if ( isset( $this->mPageTitleActionText
) ) {
448 return $this->mPageTitleActionText
;
453 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
455 * @param $policy string The literal string to output as the contents of
456 * the meta tag. Will be parsed according to the spec and output in
460 public function setRobotPolicy( $policy ) {
461 $policy = explode( ',', $policy );
462 $policy = array_map( 'trim', $policy );
464 # The default policy is follow, so if nothing is said explicitly, we
466 if( in_array( 'nofollow', $policy ) ) {
467 $this->mFollowPolicy
= 'nofollow';
469 $this->mFollowPolicy
= 'follow';
472 if( in_array( 'noindex', $policy ) ) {
473 $this->mIndexPolicy
= 'noindex';
475 $this->mIndexPolicy
= 'index';
480 * Set the index policy for the page, but leave the follow policy un-
483 * @param $policy string Either 'index' or 'noindex'.
486 public function setIndexPolicy( $policy ) {
487 $policy = trim( $policy );
488 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
489 $this->mIndexPolicy
= $policy;
494 * Set the follow policy for the page, but leave the index policy un-
497 * @param $policy string Either 'follow' or 'nofollow'.
500 public function setFollowPolicy( $policy ) {
501 $policy = trim( $policy );
502 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
503 $this->mFollowPolicy
= $policy;
508 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
510 public function setHTMLTitle( $name ) {
511 $this->mHTMLtitle
= $name;
515 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
516 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
517 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
518 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
520 public function setPageTitle( $name ) {
522 $name = $wgContLang->convert( $name, true );
523 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
524 # but leave "<i>foobar</i>" alone
525 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
526 $this->mPagetitle
= $nameWithTags;
528 $taction = $this->getPageTitleActionText();
529 if( !empty( $taction ) ) {
530 $name .= ' - '.$taction;
533 # change "<i>foo&bar</i>" to "foo&bar"
534 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
537 public function setTitle( $t ) {
541 public function getTitle() {
542 if ( $this->mTitle
instanceof Title
) {
543 return $this->mTitle
;
546 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
552 public function getHTMLTitle() { return $this->mHTMLtitle
; }
553 public function getPageTitle() { return $this->mPagetitle
; }
554 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
555 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
556 public function getSubtitle() { return $this->mSubtitle
; }
557 public function isArticle() { return $this->mIsarticle
; }
558 public function setPrintable() { $this->mPrintable
= true; }
559 public function isPrintable() { return $this->mPrintable
; }
560 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
561 public function isSyndicated() { return $this->mShowFeedLinks
; }
562 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
563 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
564 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
565 public function getOnloadHandler() { return $this->mOnloadHandler
; }
566 public function disable() { $this->mDoNothing
= true; }
567 public function isDisabled() { return $this->mDoNothing
; }
569 public function setArticleRelated( $v ) {
570 $this->mIsArticleRelated
= $v;
572 $this->mIsarticle
= false;
575 public function setArticleFlag( $v ) {
576 $this->mIsarticle
= $v;
578 $this->mIsArticleRelated
= $v;
582 public function isArticleRelated() { return $this->mIsArticleRelated
; }
584 public function getLanguageLinks() { return $this->mLanguageLinks
; }
585 public function addLanguageLinks($newLinkArray) {
586 $this->mLanguageLinks +
= $newLinkArray;
588 public function setLanguageLinks($newLinkArray) {
589 $this->mLanguageLinks
= $newLinkArray;
592 public function getCategoryLinks() {
593 return $this->mCategoryLinks
;
597 * Add an array of categories, with names in the keys
599 public function addCategoryLinks( $categories ) {
600 global $wgUser, $wgContLang;
602 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
606 # Add the links to a LinkBatch
607 $arr = array( NS_CATEGORY
=> $categories );
609 $lb->setArray( $arr );
611 # Fetch existence plus the hiddencat property
612 $dbr = wfGetDB( DB_SLAVE
);
613 $pageTable = $dbr->tableName( 'page' );
614 $where = $lb->constructSet( 'page', $dbr );
615 $propsTable = $dbr->tableName( 'page_props' );
616 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
617 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
618 $res = $dbr->query( $sql, __METHOD__
);
620 # Add the results to the link cache
621 $lb->addResultToCache( LinkCache
::singleton(), $res );
623 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
624 $categories = array_combine( array_keys( $categories ),
625 array_fill( 0, count( $categories ), 'normal' ) );
627 # Mark hidden categories
628 foreach ( $res as $row ) {
629 if ( isset( $row->pp_value
) ) {
630 $categories[$row->page_title
] = 'hidden';
634 # Add the remaining categories to the skin
635 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
636 $sk = $wgUser->getSkin();
637 foreach ( $categories as $category => $type ) {
638 $origcategory = $category;
639 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
640 $wgContLang->findVariantLink( $category, $title, true );
641 if ( $category != $origcategory )
642 if ( array_key_exists( $category, $categories ) )
644 $text = $wgContLang->convertHtml( $title->getText() );
645 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
650 public function setCategoryLinks($categories) {
651 $this->mCategoryLinks
= array();
652 $this->addCategoryLinks($categories);
655 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
656 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
658 public function disallowUserJs() { $this->mAllowUserJs
= false; }
659 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
661 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
662 public function addHTML( $text ) { $this->mBodytext
.= $text; }
663 public function clearHTML() { $this->mBodytext
= ''; }
664 public function getHTML() { return $this->mBodytext
; }
665 public function debug( $text ) { $this->mDebugtext
.= $text; }
668 public function setParserOptions( $options ) {
669 wfDeprecated( __METHOD__
);
670 return $this->parserOptions( $options );
673 public function parserOptions( $options = null ) {
674 if ( !$this->mParserOptions
) {
675 $this->mParserOptions
= new ParserOptions
;
677 return wfSetVar( $this->mParserOptions
, $options );
681 * Set the revision ID which will be seen by the wiki text parser
682 * for things such as embedded {{REVISIONID}} variable use.
683 * @param mixed $revid an integer, or NULL
684 * @return mixed previous value
686 public function setRevisionId( $revid ) {
687 $val = is_null( $revid ) ?
null : intval( $revid );
688 return wfSetVar( $this->mRevisionId
, $val );
691 public function getRevisionId() {
692 return $this->mRevisionId
;
696 * Convert wikitext to HTML and add it to the buffer
697 * Default assumes that the current page title will
700 * @param string $text
701 * @param bool $linestart
703 public function addWikiText( $text, $linestart = true ) {
704 $title = $this->getTitle(); // Work arround E_STRICT
705 $this->addWikiTextTitle( $text, $title, $linestart );
708 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
709 $this->addWikiTextTitle($text, $title, $linestart);
712 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
713 $this->addWikiTextTitle( $text, $title, $linestart, true );
716 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
719 wfProfileIn( __METHOD__
);
721 wfIncrStats( 'pcache_not_possible' );
723 $popts = $this->parserOptions();
724 $oldTidy = $popts->setTidy( $tidy );
726 $parserOutput = $wgParser->parse( $text, $title, $popts,
727 $linestart, true, $this->mRevisionId
);
729 $popts->setTidy( $oldTidy );
731 $this->addParserOutput( $parserOutput );
733 wfProfileOut( __METHOD__
);
738 * @param ParserOutput object &$parserOutput
740 public function addParserOutputNoText( &$parserOutput ) {
741 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
743 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
744 $this->addCategoryLinks( $parserOutput->getCategories() );
745 $this->mNewSectionLink
= $parserOutput->getNewSection();
746 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
748 if( is_null( $wgExemptFromUserRobotsControl ) ) {
749 $bannedNamespaces = $wgContentNamespaces;
751 $bannedNamespaces = $wgExemptFromUserRobotsControl;
753 if( !in_array( $this->getTitle()->getNamespace(), $bannedNamespaces ) ) {
754 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
756 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
759 $this->mParseWarnings
= $parserOutput->getWarnings();
760 if ( $parserOutput->getCacheTime() == -1 ) {
761 $this->enableClientCache( false );
763 $this->mNoGallery
= $parserOutput->getNoGallery();
764 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
766 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
767 if ( isset( $this->mTemplateIds
[$ns] ) ) {
768 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
770 $this->mTemplateIds
[$ns] = $dbks;
774 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
775 $this->setPageTitle( $dt );
776 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
777 $this->setPageTitle( $title );
779 // Hooks registered in the object
780 global $wgParserOutputHooks;
781 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
782 list( $hookName, $data ) = $hookInfo;
783 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
784 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
788 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
793 * @param ParserOutput &$parserOutput
795 function addParserOutput( &$parserOutput ) {
796 $this->addParserOutputNoText( $parserOutput );
797 $text = $parserOutput->getText();
798 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
799 $this->addHTML( $text );
803 * Add wikitext to the buffer, assuming that this is the primary text for a page view
804 * Saves the text into the parser cache if possible.
806 * @param string $text
807 * @param Article $article
809 * @deprecated Use Article::outputWikitext
811 public function addPrimaryWikiText( $text, $article, $cache = true ) {
814 wfDeprecated( __METHOD__
);
816 $popts = $this->parserOptions();
817 $popts->setTidy(true);
818 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
819 $popts, true, true, $this->mRevisionId
);
820 $popts->setTidy(false);
821 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
822 $parserCache = ParserCache
::singleton();
823 $parserCache->save( $parserOutput, $article, $popts);
826 $this->addParserOutput( $parserOutput );
830 * @deprecated use addWikiTextTidy()
832 public function addSecondaryWikiText( $text, $linestart = true ) {
833 wfDeprecated( __METHOD__
);
834 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
838 * Add wikitext with tidy enabled
840 public function addWikiTextTidy( $text, $linestart = true ) {
841 $title = $this->getTitle();
842 $this->addWikiTextTitleTidy($text, $title, $linestart);
847 * Add the output of a QuickTemplate to the output buffer
849 * @param QuickTemplate $template
851 public function addTemplate( &$template ) {
853 $template->execute();
854 $this->addHTML( ob_get_contents() );
859 * Parse wikitext and return the HTML.
861 * @param string $text
862 * @param bool $linestart Is this the start of a line?
863 * @param bool $interface ??
865 public function parse( $text, $linestart = true, $interface = false ) {
867 if( is_null( $this->getTitle() ) ) {
868 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
870 $popts = $this->parserOptions();
871 if ( $interface) { $popts->setInterfaceMessage(true); }
872 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
873 $linestart, true, $this->mRevisionId
);
874 if ( $interface) { $popts->setInterfaceMessage(false); }
875 return $parserOutput->getText();
878 /** Parse wikitext, strip paragraphs, and return the HTML. */
879 public function parseInline( $text, $linestart = true, $interface = false ) {
880 $parsed = $this->parse( $text, $linestart, $interface );
883 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
891 * @param Article $article
896 * @return bool True if successful, else false.
898 public function tryParserCache( &$article ) {
899 wfDeprecated( __METHOD__
);
900 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
902 if ($parserOutput !== false) {
903 $this->addParserOutput( $parserOutput );
911 * @param int $maxage Maximum cache time on the Squid, in seconds.
913 public function setSquidMaxage( $maxage ) {
914 $this->mSquidMaxage
= $maxage;
918 * Use enableClientCache(false) to force it to send nocache headers
921 public function enableClientCache( $state ) {
922 return wfSetVar( $this->mEnableClientCache
, $state );
925 function getCacheVaryCookies() {
926 global $wgCookiePrefix, $wgCacheVaryCookies;
928 if ( $cookies === null ) {
929 $cookies = array_merge(
931 "{$wgCookiePrefix}Token",
932 "{$wgCookiePrefix}LoggedOut",
937 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
942 function uncacheableBecauseRequestVars() {
944 return $wgRequest->getText('useskin', false) === false
945 && $wgRequest->getText('uselang', false) === false;
949 * Check if the request has a cache-varying cookie header
950 * If it does, it's very important that we don't allow public caching
952 function haveCacheVaryCookies() {
954 $cookieHeader = $wgRequest->getHeader( 'cookie' );
955 if ( $cookieHeader === false ) {
958 $cvCookies = $this->getCacheVaryCookies();
959 foreach ( $cvCookies as $cookieName ) {
960 # Check for a simple string match, like the way squid does it
961 if ( strpos( $cookieHeader, $cookieName ) ) {
962 wfDebug( __METHOD__
.": found $cookieName\n" );
966 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
970 /** Get a complete X-Vary-Options header */
971 public function getXVO() {
972 $cvCookies = $this->getCacheVaryCookies();
973 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
975 foreach ( $cvCookies as $cookieName ) {
981 $xvo .= 'string-contains=' . $cookieName;
986 public function sendCacheControl() {
987 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
989 $response = $wgRequest->response();
990 if ($wgUseETag && $this->mETag
)
991 $response->header("ETag: $this->mETag");
993 # don't serve compressed data to clients who can't handle it
994 # maintain different caches for logged-in users and non-logged in ones
995 $response->header( 'Vary: Accept-Encoding, Cookie' );
998 # Add an X-Vary-Options header for Squid with Wikimedia patches
999 $response->header( $this->getXVO() );
1002 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1003 if( $wgUseSquid && session_id() == '' &&
1004 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1007 # We'll purge the proxy cache explicitly, but require end user agents
1008 # to revalidate against the proxy on each visit.
1009 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1010 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1011 # start with a shorter timeout for initial testing
1012 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1013 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1014 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1016 # We'll purge the proxy cache for anons explicitly, but require end user agents
1017 # to revalidate against the proxy on each visit.
1018 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1019 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1020 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1021 # start with a shorter timeout for initial testing
1022 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1023 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1026 # We do want clients to cache if they can, but they *must* check for updates
1027 # on revisiting the page.
1028 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1029 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1030 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1032 if($this->mLastModified
) {
1033 $response->header( "Last-Modified: {$this->mLastModified}" );
1036 wfDebug( __METHOD__
. ": no caching **\n", false );
1038 # In general, the absence of a last modified header should be enough to prevent
1039 # the client from using its cache. We send a few other things just to make sure.
1040 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1041 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1042 $response->header( 'Pragma: no-cache' );
1047 * Finally, all the text has been munged and accumulated into
1048 * the object, let's actually output it:
1050 public function output() {
1051 global $wgUser, $wgOutputEncoding, $wgRequest;
1052 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1053 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
1054 global $wgEnableMWSuggest, $wgUniversalEditButton;
1057 if( $this->mDoNothing
){
1060 wfProfileIn( __METHOD__
);
1061 if ( '' != $this->mRedirect
) {
1062 # Standards require redirect URLs to be absolute
1063 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1064 if( $this->mRedirectCode
== '301') {
1065 if( !$wgDebugRedirects ) {
1066 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1068 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1070 $this->sendCacheControl();
1072 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1073 if( $wgDebugRedirects ) {
1074 $url = htmlspecialchars( $this->mRedirect
);
1075 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1076 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1077 print "</body>\n</html>\n";
1079 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1081 wfProfileOut( __METHOD__
);
1084 elseif ( $this->mStatusCode
)
1086 $statusMessage = array(
1088 101 => 'Switching Protocols',
1089 102 => 'Processing',
1093 203 => 'Non-Authoritative Information',
1094 204 => 'No Content',
1095 205 => 'Reset Content',
1096 206 => 'Partial Content',
1097 207 => 'Multi-Status',
1098 300 => 'Multiple Choices',
1099 301 => 'Moved Permanently',
1102 304 => 'Not Modified',
1104 307 => 'Temporary Redirect',
1105 400 => 'Bad Request',
1106 401 => 'Unauthorized',
1107 402 => 'Payment Required',
1110 405 => 'Method Not Allowed',
1111 406 => 'Not Acceptable',
1112 407 => 'Proxy Authentication Required',
1113 408 => 'Request Timeout',
1116 411 => 'Length Required',
1117 412 => 'Precondition Failed',
1118 413 => 'Request Entity Too Large',
1119 414 => 'Request-URI Too Large',
1120 415 => 'Unsupported Media Type',
1121 416 => 'Request Range Not Satisfiable',
1122 417 => 'Expectation Failed',
1123 422 => 'Unprocessable Entity',
1125 424 => 'Failed Dependency',
1126 500 => 'Internal Server Error',
1127 501 => 'Not Implemented',
1128 502 => 'Bad Gateway',
1129 503 => 'Service Unavailable',
1130 504 => 'Gateway Timeout',
1131 505 => 'HTTP Version Not Supported',
1132 507 => 'Insufficient Storage'
1135 if ( $statusMessage[$this->mStatusCode
] )
1136 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1139 $sk = $wgUser->getSkin();
1141 // add our core scripts to output
1142 $this->addCoreScripts2Top();
1145 $this->addScriptFile( 'ajax.js' );
1147 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1149 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1150 $this->addScriptFile( 'ajaxwatch.js' );
1153 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1154 $this->addScriptFile( 'mwsuggest.js' );
1158 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1159 $this->addScriptFile( 'rightclickedit.js' );
1162 if( $wgUniversalEditButton ) {
1163 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1164 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1165 // Original UniversalEditButton
1166 $this->addLink( array(
1167 'rel' => 'alternate',
1168 'type' => 'application/x-wiki',
1169 'title' => wfMsg( 'edit' ),
1170 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1172 // Alternate edit link
1173 $this->addLink( array(
1175 'title' => wfMsg( 'edit' ),
1176 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1181 # Buffer output; final headers may depend on later processing
1184 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1185 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1187 if ($this->mArticleBodyOnly
) {
1188 $this->out($this->mBodytext
);
1190 // Hook that allows last minute changes to the output page, e.g.
1191 // adding of CSS or Javascript by extensions.
1192 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1194 wfProfileIn( 'Output-skin' );
1195 $sk->outputPage( $this );
1196 wfProfileOut( 'Output-skin' );
1199 $this->sendCacheControl();
1201 wfProfileOut( __METHOD__
);
1205 * Actually output something with print(). Performs an iconv to the
1206 * output encoding, if needed.
1207 * @param string $ins The string to output
1209 public function out( $ins ) {
1210 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1211 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1214 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1215 if ( false === $outs ) { $outs = $ins; }
1223 public static function setEncodings() {
1224 global $wgInputEncoding, $wgOutputEncoding;
1227 $wgInputEncoding = strtolower( $wgInputEncoding );
1229 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1230 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1233 $wgOutputEncoding = $wgInputEncoding;
1237 * Deprecated, use wfReportTime() instead.
1241 public function reportTime() {
1242 wfDeprecated( __METHOD__
);
1243 $time = wfReportTime();
1248 * Produce a "user is blocked" page.
1250 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1253 function blockedPage( $return = true ) {
1254 global $wgUser, $wgContLang, $wgLang;
1256 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1257 $this->setRobotPolicy( 'noindex,nofollow' );
1258 $this->setArticleRelated( false );
1260 $name = User
::whoIs( $wgUser->blockedBy() );
1261 $reason = $wgUser->blockedFor();
1262 if( $reason == '' ) {
1263 $reason = wfMsg( 'blockednoreason' );
1265 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1268 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1270 $blockid = $wgUser->mBlock
->mId
;
1272 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1273 if ( $blockExpiry == 'infinity' ) {
1274 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1275 // Search for localization in 'ipboptions'
1276 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1277 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1278 if ( strpos( $option, ":" ) === false )
1280 list( $show, $value ) = explode( ":", $option );
1281 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1282 $blockExpiry = $show;
1287 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1290 if ( $wgUser->mBlock
->mAuto
) {
1291 $msg = 'autoblockedtext';
1293 $msg = 'blockedtext';
1296 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1297 * This could be a username, an ip range, or a single ip. */
1298 $intended = $wgUser->mBlock
->mAddress
;
1300 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1302 # Don't auto-return to special pages
1304 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1305 $this->returnToMain( null, $return );
1310 * Output a standard error page
1312 * @param string $title Message key for page title
1313 * @param string $msg Message key for page text
1314 * @param array $params Message parameters
1316 public function showErrorPage( $title, $msg, $params = array() ) {
1317 if ( $this->getTitle() ) {
1318 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1320 $this->setPageTitle( wfMsg( $title ) );
1321 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1322 $this->setRobotPolicy( 'noindex,nofollow' );
1323 $this->setArticleRelated( false );
1324 $this->enableClientCache( false );
1325 $this->mRedirect
= '';
1326 $this->mBodytext
= '';
1328 array_unshift( $params, 'parse' );
1329 array_unshift( $params, $msg );
1330 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1332 $this->returnToMain();
1336 * Output a standard permission error page
1338 * @param array $errors Error message keys
1340 public function showPermissionsErrorPage( $errors, $action = null )
1342 $this->mDebugtext
.= 'Original title: ' .
1343 $this->getTitle()->getPrefixedText() . "\n";
1344 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1345 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1346 $this->setRobotPolicy( 'noindex,nofollow' );
1347 $this->setArticleRelated( false );
1348 $this->enableClientCache( false );
1349 $this->mRedirect
= '';
1350 $this->mBodytext
= '';
1351 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1355 public function errorpage( $title, $msg ) {
1356 wfDeprecated( __METHOD__
);
1357 throw new ErrorPageError( $title, $msg );
1361 * Display an error page indicating that a given version of MediaWiki is
1362 * required to use it
1364 * @param mixed $version The version of MediaWiki needed to use the page
1366 public function versionRequired( $version ) {
1367 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1368 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1369 $this->setRobotPolicy( 'noindex,nofollow' );
1370 $this->setArticleRelated( false );
1371 $this->mBodytext
= '';
1373 $this->addWikiMsg( 'versionrequiredtext', $version );
1374 $this->returnToMain();
1378 * Display an error page noting that a given permission bit is required.
1380 * @param string $permission key required
1382 public function permissionRequired( $permission ) {
1385 $this->setPageTitle( wfMsg( 'badaccess' ) );
1386 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1387 $this->setRobotPolicy( 'noindex,nofollow' );
1388 $this->setArticleRelated( false );
1389 $this->mBodytext
= '';
1391 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1392 User
::getGroupsWithPermission( $permission ) );
1394 $this->addWikiMsg( 'badaccess-groups',
1395 $wgLang->commaList( $groups ),
1398 $this->addWikiMsg( 'badaccess-group0' );
1400 $this->returnToMain();
1404 * Use permissionRequired.
1407 public function sysopRequired() {
1408 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1412 * Use permissionRequired.
1415 public function developerRequired() {
1416 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1420 * Produce the stock "please login to use the wiki" page
1422 public function loginToUse() {
1423 global $wgUser, $wgContLang;
1425 if( $wgUser->isLoggedIn() ) {
1426 $this->permissionRequired( 'read' );
1430 $skin = $wgUser->getSkin();
1432 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1433 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1434 $this->setRobotPolicy( 'noindex,nofollow' );
1435 $this->setArticleFlag( false );
1437 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1438 $loginLink = $skin->link(
1440 wfMsgHtml( 'loginreqlink' ),
1442 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1443 array( 'known', 'noclasses' )
1445 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1446 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1448 # Don't return to the main page if the user can't read it
1449 # otherwise we'll end up in a pointless loop
1450 $mainPage = Title
::newMainPage();
1451 if( $mainPage->userCanRead() )
1452 $this->returnToMain( null, $mainPage );
1456 public function databaseError( $fname, $sql, $error, $errno ) {
1457 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1461 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1462 * @return string The wikitext error-messages, formatted into a list.
1464 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1465 if ($action == null) {
1466 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1469 $action_desc = wfMsgNoTrans( "action-$action" );
1470 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1473 if (count( $errors ) > 1) {
1474 $text .= '<ul class="permissions-errors">' . "\n";
1476 foreach( $errors as $error )
1479 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1484 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1491 * Display a page stating that the Wiki is in read-only mode,
1492 * and optionally show the source of the page that the user
1493 * was trying to edit. Should only be called (for this
1494 * purpose) after wfReadOnly() has returned true.
1496 * For historical reasons, this function is _also_ used to
1497 * show the error message when a user tries to edit a page
1498 * they are not allowed to edit. (Unless it's because they're
1499 * blocked, then we show blockedPage() instead.) In this
1500 * case, the second parameter should be set to true and a list
1501 * of reasons supplied as the third parameter.
1503 * @todo Needs to be split into multiple functions.
1505 * @param string $source Source code to show (or null).
1506 * @param bool $protected Is this a permissions error?
1507 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1509 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1511 $skin = $wgUser->getSkin();
1513 $this->setRobotPolicy( 'noindex,nofollow' );
1514 $this->setArticleRelated( false );
1516 // If no reason is given, just supply a default "I can't let you do
1517 // that, Dave" message. Should only occur if called by legacy code.
1518 if ( $protected && empty($reasons) ) {
1519 $reasons[] = array( 'badaccess-group0' );
1522 if ( !empty($reasons) ) {
1523 // Permissions error
1525 $this->setPageTitle( wfMsg( 'viewsource' ) );
1534 array( 'known', 'noclasses' )
1539 $this->setPageTitle( wfMsg( 'badaccess' ) );
1541 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1543 // Wiki is read only
1544 $this->setPageTitle( wfMsg( 'readonly' ) );
1545 $reason = wfReadOnlyReason();
1546 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1549 // Show source, if supplied
1550 if( is_string( $source ) ) {
1551 $this->addWikiMsg( 'viewsourcetext' );
1552 $text = Xml
::openElement( 'textarea',
1553 array( 'id' => 'wpTextbox1',
1554 'name' => 'wpTextbox1',
1555 'cols' => $wgUser->getOption( 'cols' ),
1556 'rows' => $wgUser->getOption( 'rows' ),
1557 'readonly' => 'readonly' ) );
1558 $text .= htmlspecialchars( $source );
1559 $text .= Xml
::closeElement( 'textarea' );
1560 $this->addHTML( $text );
1562 // Show templates used by this article
1563 $skin = $wgUser->getSkin();
1564 $article = new Article( $this->getTitle() );
1565 $this->addHTML( "<div class='templatesUsed'>
1566 {$skin->formatTemplates( $article->getUsedTemplates() )}
1571 # If the title doesn't exist, it's fairly pointless to print a return
1572 # link to it. After all, you just tried editing it and couldn't, so
1573 # what's there to do there?
1574 if( $this->getTitle()->exists() ) {
1575 $this->returnToMain( null, $this->getTitle() );
1580 public function fatalError( $message ) {
1581 wfDeprecated( __METHOD__
);
1582 throw new FatalError( $message );
1586 public function unexpectedValueError( $name, $val ) {
1587 wfDeprecated( __METHOD__
);
1588 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1592 public function fileCopyError( $old, $new ) {
1593 wfDeprecated( __METHOD__
);
1594 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1598 public function fileRenameError( $old, $new ) {
1599 wfDeprecated( __METHOD__
);
1600 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1604 public function fileDeleteError( $name ) {
1605 wfDeprecated( __METHOD__
);
1606 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1610 public function fileNotFoundError( $name ) {
1611 wfDeprecated( __METHOD__
);
1612 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1615 public function showFatalError( $message ) {
1616 $this->setPageTitle( wfMsg( "internalerror" ) );
1617 $this->setRobotPolicy( "noindex,nofollow" );
1618 $this->setArticleRelated( false );
1619 $this->enableClientCache( false );
1620 $this->mRedirect
= '';
1621 $this->mBodytext
= $message;
1624 public function showUnexpectedValueError( $name, $val ) {
1625 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1628 public function showFileCopyError( $old, $new ) {
1629 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1632 public function showFileRenameError( $old, $new ) {
1633 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1636 public function showFileDeleteError( $name ) {
1637 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1640 public function showFileNotFoundError( $name ) {
1641 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1645 * Add a "return to" link pointing to a specified title
1647 * @param Title $title Title to link
1648 * @param string $query Query string
1650 public function addReturnTo( $title, $query = array() ) {
1652 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1653 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1654 $title, null, array(), $query ) );
1655 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1659 * Add a "return to" link pointing to a specified title,
1660 * or the title indicated in the request, or else the main page
1662 * @param null $unused No longer used
1663 * @param Title $returnto Title to return to
1665 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1668 if ( $returnto == null ) {
1669 $returnto = $wgRequest->getText( 'returnto' );
1672 if ( $returntoquery == null ) {
1673 $returntoquery = $wgRequest->getText( 'returntoquery' );
1676 if ( '' === $returnto ) {
1677 $returnto = Title
::newMainPage();
1680 if ( is_object( $returnto ) ) {
1681 $titleObj = $returnto;
1683 $titleObj = Title
::newFromText( $returnto );
1685 if ( !is_object( $titleObj ) ) {
1686 $titleObj = Title
::newMainPage();
1689 $this->addReturnTo( $titleObj, $returntoquery );
1693 * @return string The doctype, opening <html>, and head element.
1695 public function headElement( Skin
$sk ) {
1696 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1697 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1698 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1700 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1701 if ( $sk->commonPrintStylesheet() ) {
1702 $this->addStyle( 'common/wikiprintable.css', 'print' );
1704 $sk->setupUserCss( $this );
1708 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1709 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1712 if ( '' == $this->getHTMLTitle() ) {
1713 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1716 $dir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1719 $ret .= "<!doctype html>\n";
1720 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1722 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1723 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1724 foreach($wgXhtmlNamespaces as $tag => $ns) {
1725 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1727 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1730 $ret .= "<head>\n\t<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t";
1731 $ret .= implode( "\n", array(
1732 $this->getHeadLinks(),
1733 $this->buildCssLinks(),
1734 $sk->getHeadScripts( $this ),
1735 $this->getHeadItems(),
1738 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1741 if( $wgEnableScriptLoader )
1742 $ret .= $this->getScriptLoaderJs();
1744 if ($wgUseTrackbacks && $this->isArticleRelated())
1745 $ret .= $this->getTitle()->trackbackRDF();
1747 $ret .= "</head>\n";
1751 protected function addDefaultMeta() {
1752 global $wgVersion, $wgHtml5;
1754 static $called = false;
1756 # Don't run this twice
1762 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1764 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1766 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1767 if( $p !== 'index,follow' ) {
1768 // http://www.robotstxt.org/wc/meta-user.html
1769 // Only show if it's different from the default robots policy
1770 $this->addMeta( 'robots', $p );
1773 if ( count( $this->mKeywords
) > 0 ) {
1775 "/<.*?" . ">/" => '',
1778 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1783 * @return string HTML tag links to be put in the header.
1785 public function getHeadLinks() {
1786 global $wgRequest, $wgFeed;
1788 // Ideally this should happen earlier, somewhere. :P
1789 $this->addDefaultMeta();
1793 foreach ( $this->mMetatags
as $tag ) {
1794 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1796 $tag[0] = substr( $tag[0], 5 );
1800 $tags[] = Xml
::element( 'meta',
1803 'content' => $tag[1] ) );
1805 foreach ( $this->mLinktags
as $tag ) {
1806 $tags[] = Xml
::element( 'link', $tag );
1810 foreach( $this->getSyndicationLinks() as $format => $link ) {
1811 # Use the page name for the title (accessed through $wgTitle since
1812 # there's no other way). In principle, this could lead to issues
1813 # with having the same name for different feeds corresponding to
1814 # the same page, but we can't avoid that at this low a level.
1816 $tags[] = $this->feedLink(
1819 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1822 # Recent changes feed should appear on every page (except recentchanges,
1823 # that would be redundant). Put it after the per-page feed to avoid
1824 # changing existing behavior. It's still available, probably via a
1825 # menu in your browser. Some sites might have a different feed they'd
1826 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1827 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1828 # If so, use it instead.
1830 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1831 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1833 if ( $wgOverrideSiteFeed ) {
1834 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1835 $tags[] = $this->feedLink (
1837 htmlspecialchars( $feedUrl ),
1838 wfMsg( "site-{$type}-feed", $wgSitename ) );
1841 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1842 foreach( $wgFeedClasses as $format => $class ) {
1843 $tags[] = $this->feedLink(
1845 $rctitle->getLocalURL( "feed={$format}" ),
1846 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1851 return implode( "\n\t", $tags ) . "\n";
1855 * Return URLs for each supported syndication format for this page.
1856 * @return array associating format keys with URLs
1858 public function getSyndicationLinks() {
1859 global $wgFeedClasses;
1862 if( $this->isSyndicated() ) {
1863 if( is_string( $this->getFeedAppendQuery() ) ) {
1864 $appendQuery = "&" . $this->getFeedAppendQuery();
1869 foreach( $wgFeedClasses as $format => $class ) {
1870 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1877 * Generate a <link rel/> for an RSS feed.
1879 private function feedLink( $type, $url, $text ) {
1880 return Xml
::element( 'link', array(
1881 'rel' => 'alternate',
1882 'type' => "application/$type+xml",
1888 * Add a local or specified stylesheet, with the given media options.
1889 * Meant primarily for internal use...
1891 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1892 * @param $conditional -- for IE conditional comments, specifying an IE version
1893 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1895 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1898 $options['media'] = $media;
1900 $options['condition'] = $condition;
1902 $options['dir'] = $dir;
1903 $this->styles
[$style] = $options;
1907 * Adds inline CSS styles
1908 * @param $style_css Mixed: inline CSS
1910 public function addInlineStyle( $style_css ){
1911 $this->mScripts
.= "<style type=\"text/css\">$style_css</style>";
1915 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1916 * These will be applied to various media & IE conditionals.
1918 public function buildCssLinks() {
1920 foreach( $this->styles
as $file => $options ) {
1921 $link = $this->styleLink( $file, $options );
1926 return "\t" . implode( "\n\t", $links );
1929 protected function styleLink( $style, $options ) {
1932 if( isset( $options['dir'] ) ) {
1934 $siteDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1935 if( $siteDir != $options['dir'] )
1939 if( isset( $options['media'] ) ) {
1940 $media = $this->transformCssMedia( $options['media'] );
1941 if( is_null( $media ) ) {
1948 if( substr( $style, 0, 1 ) == '/' ||
1949 substr( $style, 0, 5 ) == 'http:' ||
1950 substr( $style, 0, 6 ) == 'https:' ) {
1953 global $wgStylePath, $wgStyleVersion;
1954 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1958 'rel' => 'stylesheet',
1960 'type' => 'text/css' );
1962 $attribs['media'] = $media;
1965 $link = Xml
::element( 'link', $attribs );
1967 if( isset( $options['condition'] ) ) {
1968 $condition = htmlspecialchars( $options['condition'] );
1969 $link = "<!--[if $condition]>$link<![endif]-->";
1974 function transformCssMedia( $media ) {
1975 global $wgRequest, $wgHandheldForIPhone;
1977 // Switch in on-screen display for media testing
1979 'printable' => 'print',
1980 'handheld' => 'handheld',
1982 foreach( $switches as $switch => $targetMedia ) {
1983 if( $wgRequest->getBool( $switch ) ) {
1984 if( $media == $targetMedia ) {
1986 } elseif( $media == 'screen' ) {
1992 // Expand longer media queries as iPhone doesn't grok 'handheld'
1993 if( $wgHandheldForIPhone ) {
1994 $mediaAliases = array(
1995 'screen' => 'screen and (min-device-width: 481px)',
1996 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1999 if( isset( $mediaAliases[$media] ) ) {
2000 $media = $mediaAliases[$media];
2008 * Turn off regular page output and return an error reponse
2009 * for when rate limiting has triggered.
2011 public function rateLimited() {
2013 $this->setPageTitle(wfMsg('actionthrottled'));
2014 $this->setRobotPolicy( 'noindex,follow' );
2015 $this->setArticleRelated( false );
2016 $this->enableClientCache( false );
2017 $this->mRedirect
= '';
2019 $this->setStatusCode(503);
2020 $this->addWikiMsg( 'actionthrottledtext' );
2022 $this->returnToMain( null, $this->getTitle() );
2026 * Show an "add new section" link?
2030 public function showNewSectionLink() {
2031 return $this->mNewSectionLink
;
2035 * Forcibly hide the new section link?
2039 public function forceHideNewSectionLink() {
2040 return $this->mHideNewSectionLink
;
2044 * Show a warning about slave lag
2046 * If the lag is higher than $wgSlaveLagCritical seconds,
2047 * then the warning is a bit more obvious. If the lag is
2048 * lower than $wgSlaveLagWarning, then no warning is shown.
2050 * @param int $lag Slave lag
2052 public function showLagWarning( $lag ) {
2053 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2054 if( $lag >= $wgSlaveLagWarning ) {
2055 $message = $lag < $wgSlaveLagCritical
2058 $warning = wfMsgExt( $message, 'parse', $lag );
2059 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2064 * Add a wikitext-formatted message to the output.
2065 * This is equivalent to:
2067 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2069 public function addWikiMsg( /*...*/ ) {
2070 $args = func_get_args();
2071 $name = array_shift( $args );
2072 $this->addWikiMsgArray( $name, $args );
2076 * Add a wikitext-formatted message to the output.
2077 * Like addWikiMsg() except the parameters are taken as an array
2078 * instead of a variable argument list.
2080 * $options is passed through to wfMsgExt(), see that function for details.
2082 public function addWikiMsgArray( $name, $args, $options = array() ) {
2083 $options[] = 'parse';
2084 $text = wfMsgExt( $name, $options, $args );
2085 $this->addHTML( $text );
2089 * This function takes a number of message/argument specifications, wraps them in
2090 * some overall structure, and then parses the result and adds it to the output.
2092 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2093 * on. The subsequent arguments may either be strings, in which case they are the
2094 * message names, or arrays, in which case the first element is the message name,
2095 * and subsequent elements are the parameters to that message.
2097 * The special named parameter 'options' in a message specification array is passed
2098 * through to the $options parameter of wfMsgExt().
2100 * Don't use this for messages that are not in users interface language.
2104 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2108 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2110 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2111 $msgSpecs = func_get_args();
2112 array_shift( $msgSpecs );
2113 $msgSpecs = array_values( $msgSpecs );
2115 foreach ( $msgSpecs as $n => $spec ) {
2117 if ( is_array( $spec ) ) {
2119 $name = array_shift( $args );
2120 if ( isset( $args['options'] ) ) {
2121 $options = $args['options'];
2122 unset( $args['options'] );
2128 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2130 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );