ab575c93e633c1395ba2680857b470362ab00a31
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 );
98 array_push( $this->mKeywords
, $text );
101 function addScript( $script ) { $this->mScripts
.= "\t\t" . $script . "\n"; }
103 function addExtensionStyle( $url ) {
104 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
105 array_push( $this->mExtStyles
, $linkarr );
109 * Add a JavaScript file out of skins/common, or a given relative path.
110 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
112 function addScriptFile( $file ) {
113 global $wgStylePath, $wgStyleVersion, $wgJsMimeType, $wgScript, $wgUser;
114 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
116 if( substr( $file, 0, 1 ) == '/' ) {
119 $path = "{$wgStylePath}/common/{$file}";
121 if( $wgEnableScriptLoader ){
122 if( strpos($path, $wgScript) !== false ){
123 $reqPath = str_replace($wgScript.'?', '', $path);
124 $reqArgs = split('&', $reqPath);
127 foreach($reqArgs as $arg){
128 list($key, $var) = split('=', $arg);
132 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
133 //extract any extra param (for now just skin)
134 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '') ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
135 $this->mScriptLoaderClassList
[] = 'WT:' . $reqSet['title'] . $ext_param ;
136 //add the title revision to the key
137 $t = Title
::newFromText( $reqSet['title'] );
138 //if there is no title (don't worry we just use the $wgStyleVersion var (which should be updated on relevant commits)
140 if( $t->getLatestRevID() > $this->mLatestScriptRevID
)
141 $this->mLatestScriptRevID
= $t->getLatestRevID();
146 //check for class from path:
147 $js_class = $this->getJsClassFromPath( $path );
149 //add to the class list:
150 $this->mScriptLoaderClassList
[] = $js_class;
155 //if the script loader did not find a way to add the script than add using AddScript
157 Xml
::element( 'script',
159 'type' => $wgJsMimeType,
160 'src' => "$path?" . $this->getURIDparam(),
167 * This is the core script that is included on every page
168 * (they are requested separately to improve caching across
169 * different page load types (edit, upload, view, etc)
171 function addCoreScripts2Top(){
172 global $wgEnableScriptLoader, $wgStyleVersion,$wgJSAutoloadLocalClasses, $wgJsMimeType, $wgScriptPath, $wgEnableJS2system ;
173 //@@todo we should depricate wikibits in favor of mv_embed and native jQuery functions
175 if( $wgEnableJS2system ){
176 $core_classes = array('window.jQuery', 'mv_embed', 'wikibits');
178 $core_classes = array('wikibits');
180 if( $wgEnableScriptLoader ){
181 $this->mScripts
= $this->getScriptLoaderJs( $core_classes ) . $this->mScripts
;
184 foreach($core_classes as $s){
185 if(isset( $wgJSAutoloadLocalClasses[$s] )){
186 $so.= Xml
::element( 'script', array(
187 'type' => $wgJsMimeType,
188 'src' => "{$wgScriptPath}/{$wgJSAutoloadLocalClasses[$s]}?" . $this->getURIDparam()
194 $this->mScripts
= $so . $this->mScripts
;
197 function addScriptClass( $js_class ){
198 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgJsMimeType,
199 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath;
200 if(isset($wgJSAutoloadClasses[ $js_class ] ) ||
isset( $wgJSAutoloadLocalClasses[$js_class]) ){
201 if($wgEnableScriptLoader){
202 if( ! in_array( $js_class, $this->mScriptLoaderClassList
) ){
203 $this->mScriptLoaderClassList
[] = $js_class;
206 //do a normal load of without the script-loader:
207 $path = $wgScriptPath . '/';
208 $path.= isset($wgJSAutoloadClasses[ $js_class ] )?
$wgJSAutoloadClasses[ $js_class ]:
209 $wgJSAutoloadLocalClasses[$js_class];
211 Xml
::element( 'script',
213 'type' => $wgJsMimeType,
214 'src' => "$path?$wgStyleVersion",
222 wfDebug( __METHOD__
. " could not find js_class: " . $js_class );
223 return false; //could not find the class
226 * gets the scriptLoader javascript include
229 function getScriptLoaderJs( $forceClassAry=false ){
230 global $wgScriptPath, $wgJsMimeType, $wgStyleVersion, $wgRequest, $wgDebugJavaScript;
233 $class_list = implode(',', $this->mScriptLoaderClassList
);
235 $class_list = implode(',', $forceClassAry );
238 $debug_param = ( $wgDebugJavaScript ||
239 $wgRequest->getVal('debug')=='true' ||
240 $wgRequest->getVal('debug')=='1' )
241 ?
'&debug=true' : '';
243 //@@todo intelligent unique id generation based on svn version of file (rather than just grabbing the $wgStyleVersion var)
244 //@@todo we should check the packaged message text in this javascript file for updates and update the $mScriptLoaderURID id (in getJsClassFromPath)
246 //generate the unique request param (combine with the most recent revision id of any wiki page with the $wgStyleVersion var)
249 return Xml
::element( 'script',
251 'type' => $wgJsMimeType,
252 'src' => "$wgScriptPath/mwScriptLoader.php?class={$class_list}{$debug_param}&".$this->getURIDparam(),
257 function getURIDparam(){
258 global $wgDebugJavaScript,$wgStyleVersion;
259 if( $wgDebugJavaScript ){
260 return "urid=". time();
262 return "urid={$wgStyleVersion}_{$this->mLatestScriptRevID}";
265 function getJsClassFromPath( $path ){
266 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
268 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
269 foreach( $scriptLoaderPaths as $js_class => $js_path ){
270 $js_path = "{$wgScriptPath}/{$js_path}";
271 if($path == $js_path)
277 * Add a self-contained script tag with the given contents
278 * @param string $script JavaScript text, no <script> tags
280 function addInlineScript( $script ) {
281 global $wgJsMimeType;
282 $this->mScripts
.= "\t\t<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n\t\t$script\n\t\t/*]]>*/</script>\n";
285 function getScript() {
286 global $wgEnableScriptLoader;
287 if( $wgEnableScriptLoader ){
288 //include $this->mScripts (for anything that we could not package into the scriptloader
289 return $this->mScripts
."\n". $this->getScriptLoaderJs() . $this->getHeadItems();
291 return $this->mScripts
. $this->getHeadItems();
295 function getHeadItems() {
297 foreach ( $this->mHeadItems
as $item ) {
303 function addHeadItem( $name, $value ) {
304 $this->mHeadItems
[$name] = $value;
307 function hasHeadItem( $name ) {
308 return isset( $this->mHeadItems
[$name] );
311 function setETag($tag) { $this->mETag
= $tag; }
312 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
313 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly
; }
315 function addLink( $linkarr ) {
316 # $linkarr should be an associative array of attributes. We'll escape on output.
317 array_push( $this->mLinktags
, $linkarr );
320 # Get all links added by extensions
321 function getExtStyle() {
322 return $this->mExtStyles
;
325 function addMetadataLink( $linkarr ) {
326 # note: buggy CC software only reads first "meta" link
327 static $haveMeta = false;
328 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
329 $this->addLink( $linkarr );
334 * checkLastModified tells the client to use the client-cached page if
335 * possible. If sucessful, the OutputPage is disabled so that
336 * any future call to OutputPage->output() have no effect.
338 * Side effect: sets mLastModified for Last-Modified header
340 * @return bool True iff cache-ok headers was sent.
342 function checkLastModified( $timestamp ) {
343 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
345 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
346 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
349 if( !$wgCachePages ) {
350 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
353 if( $wgUser->getOption( 'nocache' ) ) {
354 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
358 $timestamp = wfTimestamp( TS_MW
, $timestamp );
359 $modifiedTimes = array(
360 'page' => $timestamp,
361 'user' => $wgUser->getTouched(),
362 'epoch' => $wgCacheEpoch
364 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
366 $maxModified = max( $modifiedTimes );
367 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
369 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
370 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
376 foreach ( $modifiedTimes as $name => $value ) {
377 if ( $info !== '' ) {
380 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
383 # IE sends sizes after the date like this:
384 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
385 # this breaks strtotime().
386 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
388 wfSuppressWarnings(); // E_STRICT system time bitching
389 $clientHeaderTime = strtotime( $clientHeader );
391 if ( !$clientHeaderTime ) {
392 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
395 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
397 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
398 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
399 wfDebug( __METHOD__
. ": effective Last-Modified: " .
400 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
401 if( $clientHeaderTime < $maxModified ) {
402 wfDebug( __METHOD__
. ": STALE, $info\n", false );
407 # Give a 304 response code and disable body output
408 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
409 ini_set('zlib.output_compression', 0);
410 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
411 $this->sendCacheControl();
414 // Don't output a compressed blob when using ob_gzhandler;
415 // it's technically against HTTP spec and seems to confuse
416 // Firefox when the response gets split over two packets.
417 wfClearOutputBuffers();
422 function setPageTitleActionText( $text ) {
423 $this->mPageTitleActionText
= $text;
426 function getPageTitleActionText () {
427 if ( isset( $this->mPageTitleActionText
) ) {
428 return $this->mPageTitleActionText
;
433 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
435 * @param $policy string The literal string to output as the contents of
436 * the meta tag. Will be parsed according to the spec and output in
440 public function setRobotPolicy( $policy ) {
441 $policy = explode( ',', $policy );
442 $policy = array_map( 'trim', $policy );
444 # The default policy is follow, so if nothing is said explicitly, we
446 if( in_array( 'nofollow', $policy ) ) {
447 $this->mFollowPolicy
= 'nofollow';
449 $this->mFollowPolicy
= 'follow';
452 if( in_array( 'noindex', $policy ) ) {
453 $this->mIndexPolicy
= 'noindex';
455 $this->mIndexPolicy
= 'index';
460 * Set the index policy for the page, but leave the follow policy un-
463 * @param $policy string Either 'index' or 'noindex'.
466 public function setIndexPolicy( $policy ) {
467 $policy = trim( $policy );
468 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
469 $this->mIndexPolicy
= $policy;
474 * Set the follow policy for the page, but leave the index policy un-
477 * @param $policy string Either 'follow' or 'nofollow'.
480 public function setFollowPolicy( $policy ) {
481 $policy = trim( $policy );
482 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
483 $this->mFollowPolicy
= $policy;
488 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
490 public function setHTMLTitle( $name ) {
491 $this->mHTMLtitle
= $name;
495 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
496 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
497 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
498 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
500 public function setPageTitle( $name ) {
502 $name = $wgContLang->convert( $name, true );
503 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
504 # but leave "<i>foobar</i>" alone
505 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
506 $this->mPagetitle
= $nameWithTags;
508 $taction = $this->getPageTitleActionText();
509 if( !empty( $taction ) ) {
510 $name .= ' - '.$taction;
513 # change "<i>foo&bar</i>" to "foo&bar"
514 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
517 public function setTitle( $t ) {
521 public function getTitle() {
522 if ( $this->mTitle
instanceof Title
) {
523 return $this->mTitle
;
526 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
532 public function getHTMLTitle() { return $this->mHTMLtitle
; }
533 public function getPageTitle() { return $this->mPagetitle
; }
534 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
535 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
536 public function getSubtitle() { return $this->mSubtitle
; }
537 public function isArticle() { return $this->mIsarticle
; }
538 public function setPrintable() { $this->mPrintable
= true; }
539 public function isPrintable() { return $this->mPrintable
; }
540 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
541 public function isSyndicated() { return $this->mShowFeedLinks
; }
542 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
543 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
544 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
545 public function getOnloadHandler() { return $this->mOnloadHandler
; }
546 public function disable() { $this->mDoNothing
= true; }
547 public function isDisabled() { return $this->mDoNothing
; }
549 public function setArticleRelated( $v ) {
550 $this->mIsArticleRelated
= $v;
552 $this->mIsarticle
= false;
555 public function setArticleFlag( $v ) {
556 $this->mIsarticle
= $v;
558 $this->mIsArticleRelated
= $v;
562 public function isArticleRelated() { return $this->mIsArticleRelated
; }
564 public function getLanguageLinks() { return $this->mLanguageLinks
; }
565 public function addLanguageLinks($newLinkArray) {
566 $this->mLanguageLinks +
= $newLinkArray;
568 public function setLanguageLinks($newLinkArray) {
569 $this->mLanguageLinks
= $newLinkArray;
572 public function getCategoryLinks() {
573 return $this->mCategoryLinks
;
577 * Add an array of categories, with names in the keys
579 public function addCategoryLinks( $categories ) {
580 global $wgUser, $wgContLang;
582 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
586 # Add the links to a LinkBatch
587 $arr = array( NS_CATEGORY
=> $categories );
589 $lb->setArray( $arr );
591 # Fetch existence plus the hiddencat property
592 $dbr = wfGetDB( DB_SLAVE
);
593 $pageTable = $dbr->tableName( 'page' );
594 $where = $lb->constructSet( 'page', $dbr );
595 $propsTable = $dbr->tableName( 'page_props' );
596 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
597 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
598 $res = $dbr->query( $sql, __METHOD__
);
600 # Add the results to the link cache
601 $lb->addResultToCache( LinkCache
::singleton(), $res );
603 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
604 $categories = array_combine( array_keys( $categories ),
605 array_fill( 0, count( $categories ), 'normal' ) );
607 # Mark hidden categories
608 foreach ( $res as $row ) {
609 if ( isset( $row->pp_value
) ) {
610 $categories[$row->page_title
] = 'hidden';
614 # Add the remaining categories to the skin
615 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
616 $sk = $wgUser->getSkin();
617 foreach ( $categories as $category => $type ) {
618 $origcategory = $category;
619 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
620 $wgContLang->findVariantLink( $category, $title, true );
621 if ( $category != $origcategory )
622 if ( array_key_exists( $category, $categories ) )
624 $text = $wgContLang->convertHtml( $title->getText() );
625 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
630 public function setCategoryLinks($categories) {
631 $this->mCategoryLinks
= array();
632 $this->addCategoryLinks($categories);
635 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
636 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
638 public function disallowUserJs() { $this->mAllowUserJs
= false; }
639 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
641 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
642 public function addHTML( $text ) { $this->mBodytext
.= $text; }
643 public function clearHTML() { $this->mBodytext
= ''; }
644 public function getHTML() { return $this->mBodytext
; }
645 public function debug( $text ) { $this->mDebugtext
.= $text; }
648 public function setParserOptions( $options ) {
649 wfDeprecated( __METHOD__
);
650 return $this->parserOptions( $options );
653 public function parserOptions( $options = null ) {
654 if ( !$this->mParserOptions
) {
655 $this->mParserOptions
= new ParserOptions
;
657 return wfSetVar( $this->mParserOptions
, $options );
661 * Set the revision ID which will be seen by the wiki text parser
662 * for things such as embedded {{REVISIONID}} variable use.
663 * @param mixed $revid an integer, or NULL
664 * @return mixed previous value
666 public function setRevisionId( $revid ) {
667 $val = is_null( $revid ) ?
null : intval( $revid );
668 return wfSetVar( $this->mRevisionId
, $val );
671 public function getRevisionId() {
672 return $this->mRevisionId
;
676 * Convert wikitext to HTML and add it to the buffer
677 * Default assumes that the current page title will
680 * @param string $text
681 * @param bool $linestart
683 public function addWikiText( $text, $linestart = true ) {
684 $title = $this->getTitle(); // Work arround E_STRICT
685 $this->addWikiTextTitle( $text, $title, $linestart );
688 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
689 $this->addWikiTextTitle($text, $title, $linestart);
692 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
693 $this->addWikiTextTitle( $text, $title, $linestart, true );
696 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
699 wfProfileIn( __METHOD__
);
701 wfIncrStats( 'pcache_not_possible' );
703 $popts = $this->parserOptions();
704 $oldTidy = $popts->setTidy( $tidy );
706 $parserOutput = $wgParser->parse( $text, $title, $popts,
707 $linestart, true, $this->mRevisionId
);
709 $popts->setTidy( $oldTidy );
711 $this->addParserOutput( $parserOutput );
713 wfProfileOut( __METHOD__
);
718 * @param ParserOutput object &$parserOutput
720 public function addParserOutputNoText( &$parserOutput ) {
721 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
723 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
724 $this->addCategoryLinks( $parserOutput->getCategories() );
725 $this->mNewSectionLink
= $parserOutput->getNewSection();
726 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
728 if( is_null( $wgExemptFromUserRobotsControl ) ) {
729 $bannedNamespaces = $wgContentNamespaces;
731 $bannedNamespaces = $wgExemptFromUserRobotsControl;
733 if( !in_array( $this->getTitle()->getNamespace(), $bannedNamespaces ) ) {
734 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
736 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
739 $this->addKeywords( $parserOutput );
740 $this->mParseWarnings
= $parserOutput->getWarnings();
741 if ( $parserOutput->getCacheTime() == -1 ) {
742 $this->enableClientCache( false );
744 $this->mNoGallery
= $parserOutput->getNoGallery();
745 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
747 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
748 if ( isset( $this->mTemplateIds
[$ns] ) ) {
749 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
751 $this->mTemplateIds
[$ns] = $dbks;
755 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
756 $this->setPageTitle( $dt );
757 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
758 $this->setPageTitle( $title );
760 // Hooks registered in the object
761 global $wgParserOutputHooks;
762 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
763 list( $hookName, $data ) = $hookInfo;
764 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
765 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
769 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
774 * @param ParserOutput &$parserOutput
776 function addParserOutput( &$parserOutput ) {
777 $this->addParserOutputNoText( $parserOutput );
778 $text = $parserOutput->getText();
779 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
780 $this->addHTML( $text );
784 * Add wikitext to the buffer, assuming that this is the primary text for a page view
785 * Saves the text into the parser cache if possible.
787 * @param string $text
788 * @param Article $article
790 * @deprecated Use Article::outputWikitext
792 public function addPrimaryWikiText( $text, $article, $cache = true ) {
795 wfDeprecated( __METHOD__
);
797 $popts = $this->parserOptions();
798 $popts->setTidy(true);
799 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
800 $popts, true, true, $this->mRevisionId
);
801 $popts->setTidy(false);
802 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
803 $parserCache = ParserCache
::singleton();
804 $parserCache->save( $parserOutput, $article, $popts);
807 $this->addParserOutput( $parserOutput );
811 * @deprecated use addWikiTextTidy()
813 public function addSecondaryWikiText( $text, $linestart = true ) {
814 wfDeprecated( __METHOD__
);
815 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
819 * Add wikitext with tidy enabled
821 public function addWikiTextTidy( $text, $linestart = true ) {
822 $title = $this->getTitle();
823 $this->addWikiTextTitleTidy($text, $title, $linestart);
828 * Add the output of a QuickTemplate to the output buffer
830 * @param QuickTemplate $template
832 public function addTemplate( &$template ) {
834 $template->execute();
835 $this->addHTML( ob_get_contents() );
840 * Parse wikitext and return the HTML.
842 * @param string $text
843 * @param bool $linestart Is this the start of a line?
844 * @param bool $interface ??
846 public function parse( $text, $linestart = true, $interface = false ) {
848 if( is_null( $this->getTitle() ) ) {
849 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
851 $popts = $this->parserOptions();
852 if ( $interface) { $popts->setInterfaceMessage(true); }
853 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
854 $linestart, true, $this->mRevisionId
);
855 if ( $interface) { $popts->setInterfaceMessage(false); }
856 return $parserOutput->getText();
859 /** Parse wikitext, strip paragraphs, and return the HTML. */
860 public function parseInline( $text, $linestart = true, $interface = false ) {
861 $parsed = $this->parse( $text, $linestart, $interface );
864 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
872 * @param Article $article
877 * @return bool True if successful, else false.
879 public function tryParserCache( &$article ) {
880 wfDeprecated( __METHOD__
);
881 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
883 if ($parserOutput !== false) {
884 $this->addParserOutput( $parserOutput );
892 * @param int $maxage Maximum cache time on the Squid, in seconds.
894 public function setSquidMaxage( $maxage ) {
895 $this->mSquidMaxage
= $maxage;
899 * Use enableClientCache(false) to force it to send nocache headers
902 public function enableClientCache( $state ) {
903 return wfSetVar( $this->mEnableClientCache
, $state );
906 function getCacheVaryCookies() {
907 global $wgCookiePrefix, $wgCacheVaryCookies;
909 if ( $cookies === null ) {
910 $cookies = array_merge(
912 "{$wgCookiePrefix}Token",
913 "{$wgCookiePrefix}LoggedOut",
918 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
923 function uncacheableBecauseRequestVars() {
925 return $wgRequest->getText('useskin', false) === false
926 && $wgRequest->getText('uselang', false) === false;
930 * Check if the request has a cache-varying cookie header
931 * If it does, it's very important that we don't allow public caching
933 function haveCacheVaryCookies() {
935 $cookieHeader = $wgRequest->getHeader( 'cookie' );
936 if ( $cookieHeader === false ) {
939 $cvCookies = $this->getCacheVaryCookies();
940 foreach ( $cvCookies as $cookieName ) {
941 # Check for a simple string match, like the way squid does it
942 if ( strpos( $cookieHeader, $cookieName ) ) {
943 wfDebug( __METHOD__
.": found $cookieName\n" );
947 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
951 /** Get a complete X-Vary-Options header */
952 public function getXVO() {
953 $cvCookies = $this->getCacheVaryCookies();
954 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
956 foreach ( $cvCookies as $cookieName ) {
962 $xvo .= 'string-contains=' . $cookieName;
967 public function sendCacheControl() {
968 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
970 $response = $wgRequest->response();
971 if ($wgUseETag && $this->mETag
)
972 $response->header("ETag: $this->mETag");
974 # don't serve compressed data to clients who can't handle it
975 # maintain different caches for logged-in users and non-logged in ones
976 $response->header( 'Vary: Accept-Encoding, Cookie' );
978 # Add an X-Vary-Options header for Squid with Wikimedia patches
979 $response->header( $this->getXVO() );
981 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
982 if( $wgUseSquid && session_id() == '' &&
983 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
986 # We'll purge the proxy cache explicitly, but require end user agents
987 # to revalidate against the proxy on each visit.
988 # Surrogate-Control controls our Squid, Cache-Control downstream caches
989 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
990 # start with a shorter timeout for initial testing
991 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
992 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
993 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
995 # We'll purge the proxy cache for anons explicitly, but require end user agents
996 # to revalidate against the proxy on each visit.
997 # IMPORTANT! The Squid needs to replace the Cache-Control header with
998 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
999 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1000 # start with a shorter timeout for initial testing
1001 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1002 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1005 # We do want clients to cache if they can, but they *must* check for updates
1006 # on revisiting the page.
1007 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1008 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1009 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1011 if($this->mLastModified
) {
1012 $response->header( "Last-Modified: {$this->mLastModified}" );
1015 wfDebug( __METHOD__
. ": no caching **\n", false );
1017 # In general, the absence of a last modified header should be enough to prevent
1018 # the client from using its cache. We send a few other things just to make sure.
1019 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1020 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1021 $response->header( 'Pragma: no-cache' );
1026 * Finally, all the text has been munged and accumulated into
1027 * the object, let's actually output it:
1029 public function output() {
1030 global $wgUser, $wgOutputEncoding, $wgRequest;
1031 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1032 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
1033 global $wgEnableMWSuggest, $wgUniversalEditButton;
1036 if( $this->mDoNothing
){
1039 wfProfileIn( __METHOD__
);
1040 if ( '' != $this->mRedirect
) {
1041 # Standards require redirect URLs to be absolute
1042 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1043 if( $this->mRedirectCode
== '301') {
1044 if( !$wgDebugRedirects ) {
1045 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1047 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1049 $this->sendCacheControl();
1051 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1052 if( $wgDebugRedirects ) {
1053 $url = htmlspecialchars( $this->mRedirect
);
1054 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1055 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1056 print "</body>\n</html>\n";
1058 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1060 wfProfileOut( __METHOD__
);
1063 elseif ( $this->mStatusCode
)
1065 $statusMessage = array(
1067 101 => 'Switching Protocols',
1068 102 => 'Processing',
1072 203 => 'Non-Authoritative Information',
1073 204 => 'No Content',
1074 205 => 'Reset Content',
1075 206 => 'Partial Content',
1076 207 => 'Multi-Status',
1077 300 => 'Multiple Choices',
1078 301 => 'Moved Permanently',
1081 304 => 'Not Modified',
1083 307 => 'Temporary Redirect',
1084 400 => 'Bad Request',
1085 401 => 'Unauthorized',
1086 402 => 'Payment Required',
1089 405 => 'Method Not Allowed',
1090 406 => 'Not Acceptable',
1091 407 => 'Proxy Authentication Required',
1092 408 => 'Request Timeout',
1095 411 => 'Length Required',
1096 412 => 'Precondition Failed',
1097 413 => 'Request Entity Too Large',
1098 414 => 'Request-URI Too Large',
1099 415 => 'Unsupported Media Type',
1100 416 => 'Request Range Not Satisfiable',
1101 417 => 'Expectation Failed',
1102 422 => 'Unprocessable Entity',
1104 424 => 'Failed Dependency',
1105 500 => 'Internal Server Error',
1106 501 => 'Not Implemented',
1107 502 => 'Bad Gateway',
1108 503 => 'Service Unavailable',
1109 504 => 'Gateway Timeout',
1110 505 => 'HTTP Version Not Supported',
1111 507 => 'Insufficient Storage'
1114 if ( $statusMessage[$this->mStatusCode
] )
1115 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1118 $sk = $wgUser->getSkin();
1120 //add our core scripts to output
1121 $this->addCoreScripts2Top();
1124 $this->addScriptFile( 'ajax.js' );
1126 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1128 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1129 $this->addScriptFile( 'ajaxwatch.js' );
1132 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1133 $this->addScriptFile( 'mwsuggest.js' );
1137 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1138 $this->addScriptFile( 'rightclickedit.js' );
1141 if( $wgUniversalEditButton ) {
1142 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1143 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1144 // Original UniversalEditButton
1145 $this->addLink( array(
1146 'rel' => 'alternate',
1147 'type' => 'application/x-wiki',
1148 'title' => wfMsg( 'edit' ),
1149 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1151 // Alternate edit link
1152 $this->addLink( array(
1154 'title' => wfMsg( 'edit' ),
1155 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1160 # Buffer output; final headers may depend on later processing
1163 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1164 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1166 if ($this->mArticleBodyOnly
) {
1167 $this->out($this->mBodytext
);
1169 // Hook that allows last minute changes to the output page, e.g.
1170 // adding of CSS or Javascript by extensions.
1171 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1173 wfProfileIn( 'Output-skin' );
1174 $sk->outputPage( $this );
1175 wfProfileOut( 'Output-skin' );
1178 $this->sendCacheControl();
1180 wfProfileOut( __METHOD__
);
1184 * Actually output something with print(). Performs an iconv to the
1185 * output encoding, if needed.
1186 * @param string $ins The string to output
1188 public function out( $ins ) {
1189 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1190 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1193 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1194 if ( false === $outs ) { $outs = $ins; }
1202 public static function setEncodings() {
1203 global $wgInputEncoding, $wgOutputEncoding;
1206 $wgInputEncoding = strtolower( $wgInputEncoding );
1208 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1209 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1212 $wgOutputEncoding = $wgInputEncoding;
1216 * Deprecated, use wfReportTime() instead.
1220 public function reportTime() {
1221 wfDeprecated( __METHOD__
);
1222 $time = wfReportTime();
1227 * Produce a "user is blocked" page.
1229 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1232 function blockedPage( $return = true ) {
1233 global $wgUser, $wgContLang, $wgLang;
1235 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1236 $this->setRobotPolicy( 'noindex,nofollow' );
1237 $this->setArticleRelated( false );
1239 $name = User
::whoIs( $wgUser->blockedBy() );
1240 $reason = $wgUser->blockedFor();
1241 if( $reason == '' ) {
1242 $reason = wfMsg( 'blockednoreason' );
1244 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1247 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1249 $blockid = $wgUser->mBlock
->mId
;
1251 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1252 if ( $blockExpiry == 'infinity' ) {
1253 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1254 // Search for localization in 'ipboptions'
1255 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1256 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1257 if ( strpos( $option, ":" ) === false )
1259 list( $show, $value ) = explode( ":", $option );
1260 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1261 $blockExpiry = $show;
1266 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1269 if ( $wgUser->mBlock
->mAuto
) {
1270 $msg = 'autoblockedtext';
1272 $msg = 'blockedtext';
1275 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1276 * This could be a username, an ip range, or a single ip. */
1277 $intended = $wgUser->mBlock
->mAddress
;
1279 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1281 # Don't auto-return to special pages
1283 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1284 $this->returnToMain( null, $return );
1289 * Output a standard error page
1291 * @param string $title Message key for page title
1292 * @param string $msg Message key for page text
1293 * @param array $params Message parameters
1295 public function showErrorPage( $title, $msg, $params = array() ) {
1296 if ( $this->getTitle() ) {
1297 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1299 $this->setPageTitle( wfMsg( $title ) );
1300 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1301 $this->setRobotPolicy( 'noindex,nofollow' );
1302 $this->setArticleRelated( false );
1303 $this->enableClientCache( false );
1304 $this->mRedirect
= '';
1305 $this->mBodytext
= '';
1307 array_unshift( $params, 'parse' );
1308 array_unshift( $params, $msg );
1309 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1311 $this->returnToMain();
1315 * Output a standard permission error page
1317 * @param array $errors Error message keys
1319 public function showPermissionsErrorPage( $errors, $action = null )
1321 $this->mDebugtext
.= 'Original title: ' .
1322 $this->getTitle()->getPrefixedText() . "\n";
1323 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1324 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1325 $this->setRobotPolicy( 'noindex,nofollow' );
1326 $this->setArticleRelated( false );
1327 $this->enableClientCache( false );
1328 $this->mRedirect
= '';
1329 $this->mBodytext
= '';
1330 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1334 public function errorpage( $title, $msg ) {
1335 wfDeprecated( __METHOD__
);
1336 throw new ErrorPageError( $title, $msg );
1340 * Display an error page indicating that a given version of MediaWiki is
1341 * required to use it
1343 * @param mixed $version The version of MediaWiki needed to use the page
1345 public function versionRequired( $version ) {
1346 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1347 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1348 $this->setRobotPolicy( 'noindex,nofollow' );
1349 $this->setArticleRelated( false );
1350 $this->mBodytext
= '';
1352 $this->addWikiMsg( 'versionrequiredtext', $version );
1353 $this->returnToMain();
1357 * Display an error page noting that a given permission bit is required.
1359 * @param string $permission key required
1361 public function permissionRequired( $permission ) {
1364 $this->setPageTitle( wfMsg( 'badaccess' ) );
1365 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1366 $this->setRobotPolicy( 'noindex,nofollow' );
1367 $this->setArticleRelated( false );
1368 $this->mBodytext
= '';
1370 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1371 User
::getGroupsWithPermission( $permission ) );
1373 $this->addWikiMsg( 'badaccess-groups',
1374 $wgLang->commaList( $groups ),
1377 $this->addWikiMsg( 'badaccess-group0' );
1379 $this->returnToMain();
1383 * Use permissionRequired.
1386 public function sysopRequired() {
1387 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1391 * Use permissionRequired.
1394 public function developerRequired() {
1395 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1399 * Produce the stock "please login to use the wiki" page
1401 public function loginToUse() {
1402 global $wgUser, $wgContLang;
1404 if( $wgUser->isLoggedIn() ) {
1405 $this->permissionRequired( 'read' );
1409 $skin = $wgUser->getSkin();
1411 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1412 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1413 $this->setRobotPolicy( 'noindex,nofollow' );
1414 $this->setArticleFlag( false );
1416 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1417 $loginLink = $skin->link(
1419 wfMsgHtml( 'loginreqlink' ),
1421 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1422 array( 'known', 'noclasses' )
1424 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1425 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1427 # Don't return to the main page if the user can't read it
1428 # otherwise we'll end up in a pointless loop
1429 $mainPage = Title
::newMainPage();
1430 if( $mainPage->userCanRead() )
1431 $this->returnToMain( null, $mainPage );
1435 public function databaseError( $fname, $sql, $error, $errno ) {
1436 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1440 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1441 * @return string The wikitext error-messages, formatted into a list.
1443 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1444 if ($action == null) {
1445 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1448 $action_desc = wfMsgNoTrans( "action-$action" );
1449 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1452 if (count( $errors ) > 1) {
1453 $text .= '<ul class="permissions-errors">' . "\n";
1455 foreach( $errors as $error )
1458 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1463 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1470 * Display a page stating that the Wiki is in read-only mode,
1471 * and optionally show the source of the page that the user
1472 * was trying to edit. Should only be called (for this
1473 * purpose) after wfReadOnly() has returned true.
1475 * For historical reasons, this function is _also_ used to
1476 * show the error message when a user tries to edit a page
1477 * they are not allowed to edit. (Unless it's because they're
1478 * blocked, then we show blockedPage() instead.) In this
1479 * case, the second parameter should be set to true and a list
1480 * of reasons supplied as the third parameter.
1482 * @todo Needs to be split into multiple functions.
1484 * @param string $source Source code to show (or null).
1485 * @param bool $protected Is this a permissions error?
1486 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1488 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1490 $skin = $wgUser->getSkin();
1492 $this->setRobotPolicy( 'noindex,nofollow' );
1493 $this->setArticleRelated( false );
1495 // If no reason is given, just supply a default "I can't let you do
1496 // that, Dave" message. Should only occur if called by legacy code.
1497 if ( $protected && empty($reasons) ) {
1498 $reasons[] = array( 'badaccess-group0' );
1501 if ( !empty($reasons) ) {
1502 // Permissions error
1504 $this->setPageTitle( wfMsg( 'viewsource' ) );
1513 array( 'known', 'noclasses' )
1518 $this->setPageTitle( wfMsg( 'badaccess' ) );
1520 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1522 // Wiki is read only
1523 $this->setPageTitle( wfMsg( 'readonly' ) );
1524 $reason = wfReadOnlyReason();
1525 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1528 // Show source, if supplied
1529 if( is_string( $source ) ) {
1530 $this->addWikiMsg( 'viewsourcetext' );
1531 $text = Xml
::openElement( 'textarea',
1532 array( 'id' => 'wpTextbox1',
1533 'name' => 'wpTextbox1',
1534 'cols' => $wgUser->getOption( 'cols' ),
1535 'rows' => $wgUser->getOption( 'rows' ),
1536 'readonly' => 'readonly' ) );
1537 $text .= htmlspecialchars( $source );
1538 $text .= Xml
::closeElement( 'textarea' );
1539 $this->addHTML( $text );
1541 // Show templates used by this article
1542 $skin = $wgUser->getSkin();
1543 $article = new Article( $this->getTitle() );
1544 $this->addHTML( "<div class='templatesUsed'>
1545 {$skin->formatTemplates( $article->getUsedTemplates() )}
1550 # If the title doesn't exist, it's fairly pointless to print a return
1551 # link to it. After all, you just tried editing it and couldn't, so
1552 # what's there to do there?
1553 if( $this->getTitle()->exists() ) {
1554 $this->returnToMain( null, $this->getTitle() );
1559 public function fatalError( $message ) {
1560 wfDeprecated( __METHOD__
);
1561 throw new FatalError( $message );
1565 public function unexpectedValueError( $name, $val ) {
1566 wfDeprecated( __METHOD__
);
1567 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1571 public function fileCopyError( $old, $new ) {
1572 wfDeprecated( __METHOD__
);
1573 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1577 public function fileRenameError( $old, $new ) {
1578 wfDeprecated( __METHOD__
);
1579 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1583 public function fileDeleteError( $name ) {
1584 wfDeprecated( __METHOD__
);
1585 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1589 public function fileNotFoundError( $name ) {
1590 wfDeprecated( __METHOD__
);
1591 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1594 public function showFatalError( $message ) {
1595 $this->setPageTitle( wfMsg( "internalerror" ) );
1596 $this->setRobotPolicy( "noindex,nofollow" );
1597 $this->setArticleRelated( false );
1598 $this->enableClientCache( false );
1599 $this->mRedirect
= '';
1600 $this->mBodytext
= $message;
1603 public function showUnexpectedValueError( $name, $val ) {
1604 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1607 public function showFileCopyError( $old, $new ) {
1608 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1611 public function showFileRenameError( $old, $new ) {
1612 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1615 public function showFileDeleteError( $name ) {
1616 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1619 public function showFileNotFoundError( $name ) {
1620 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1624 * Add a "return to" link pointing to a specified title
1626 * @param Title $title Title to link
1627 * @param string $query Query string
1629 public function addReturnTo( $title, $query ) {
1631 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1632 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1633 $title, null, array(), $query ) );
1634 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1638 * Add a "return to" link pointing to a specified title,
1639 * or the title indicated in the request, or else the main page
1641 * @param null $unused No longer used
1642 * @param Title $returnto Title to return to
1644 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1647 if ( $returnto == null ) {
1648 $returnto = $wgRequest->getText( 'returnto' );
1651 if ( $returntoquery == null ) {
1652 $returntoquery = $wgRequest->getText( 'returntoquery' );
1655 if ( '' === $returnto ) {
1656 $returnto = Title
::newMainPage();
1659 if ( is_object( $returnto ) ) {
1660 $titleObj = $returnto;
1662 $titleObj = Title
::newFromText( $returnto );
1664 if ( !is_object( $titleObj ) ) {
1665 $titleObj = Title
::newMainPage();
1668 $this->addReturnTo( $titleObj, $returntoquery );
1672 * This function takes the title (first item of mGoodLinks), categories,
1673 * existing and broken links for the page
1674 * and uses the first 10 of them for META keywords
1676 * @param ParserOutput &$parserOutput
1678 private function addKeywords( &$parserOutput ) {
1680 // Get an array of keywords if there are more than one
1681 // variant of the site language
1682 $text = $wgContLang->autoConvertToAllVariants( $this->getTitle()->getPrefixedText());
1683 // array_values: We needn't to merge variant's code name
1684 // into $this->mKeywords;
1685 // array_unique: We should insert a keyword just for once
1686 if( is_array( $text ))
1687 $text = array_unique( array_values( $text ));
1688 $this->addKeyword( $text );
1690 $links2d =& $parserOutput->getLinks();
1691 if ( !is_array( $links2d ) ) {
1694 foreach ( $links2d as $dbkeys ) {
1695 foreach( $dbkeys as $dbkey => $unused ) {
1696 $dbkey = $wgContLang->autoConvertToAllVariants( $dbkey );
1697 if( is_array( $dbkey ))
1698 $dbkey = array_unique( array_values( $dbkey ));
1699 $this->addKeyword( $dbkey );
1700 if ( ++
$count > 10 ) {
1708 * @return string The doctype, opening <html>, and head element.
1710 public function headElement( Skin
$sk ) {
1711 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1712 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1713 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1715 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1716 if ( $sk->commonPrintStylesheet() ) {
1717 $this->addStyle( 'common/wikiprintable.css', 'print' );
1719 $sk->setupUserCss( $this );
1723 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1724 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1728 $ret .= "<!doctype html>\n";
1730 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1733 if ( '' == $this->getHTMLTitle() ) {
1734 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1737 $dir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1738 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1739 foreach($wgXhtmlNamespaces as $tag => $ns) {
1740 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1742 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1743 $ret .= "<head>\n\t<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t";
1744 $ret .= implode( "\n", array(
1745 $this->getHeadLinks(),
1746 $this->buildCssLinks(),
1747 $sk->getHeadScripts( $this ),
1748 $this->getHeadItems(),
1751 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1754 if( $wgEnableScriptLoader )
1755 $ret .= $this->getScriptLoaderJs();
1757 if ($wgUseTrackbacks && $this->isArticleRelated())
1758 $ret .= $this->getTitle()->trackbackRDF();
1760 $ret .= "</head>\n";
1764 protected function addDefaultMeta() {
1765 global $wgVersion, $wgHtml5;
1767 static $called = false;
1769 # Don't run this twice
1775 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1777 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1779 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1780 if( $p !== 'index,follow' ) {
1781 // http://www.robotstxt.org/wc/meta-user.html
1782 // Only show if it's different from the default robots policy
1783 $this->addMeta( 'robots', $p );
1786 if ( count( $this->mKeywords
) > 0 ) {
1788 "/<.*?" . ">/" => '',
1791 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1796 * @return string HTML tag links to be put in the header.
1798 public function getHeadLinks() {
1799 global $wgRequest, $wgFeed;
1801 // Ideally this should happen earlier, somewhere. :P
1802 $this->addDefaultMeta();
1806 foreach ( $this->mMetatags
as $tag ) {
1807 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1809 $tag[0] = substr( $tag[0], 5 );
1813 $tags[] = Xml
::element( 'meta',
1816 'content' => $tag[1] ) );
1818 foreach ( $this->mLinktags
as $tag ) {
1819 $tags[] = Xml
::element( 'link', $tag );
1823 foreach( $this->getSyndicationLinks() as $format => $link ) {
1824 # Use the page name for the title (accessed through $wgTitle since
1825 # there's no other way). In principle, this could lead to issues
1826 # with having the same name for different feeds corresponding to
1827 # the same page, but we can't avoid that at this low a level.
1829 $tags[] = $this->feedLink(
1832 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1835 # Recent changes feed should appear on every page (except recentchanges,
1836 # that would be redundant). Put it after the per-page feed to avoid
1837 # changing existing behavior. It's still available, probably via a
1838 # menu in your browser. Some sites might have a different feed they'd
1839 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1840 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1841 # If so, use it instead.
1843 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1844 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1846 if ( $wgOverrideSiteFeed ) {
1847 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1848 $tags[] = $this->feedLink (
1850 htmlspecialchars( $feedUrl ),
1851 wfMsg( "site-{$type}-feed", $wgSitename ) );
1854 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1855 foreach( $wgFeedClasses as $format => $class ) {
1856 $tags[] = $this->feedLink(
1858 $rctitle->getLocalURL( "feed={$format}" ),
1859 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1864 return implode( "\n\t", $tags ) . "\n";
1868 * Return URLs for each supported syndication format for this page.
1869 * @return array associating format keys with URLs
1871 public function getSyndicationLinks() {
1872 global $wgFeedClasses;
1875 if( $this->isSyndicated() ) {
1876 if( is_string( $this->getFeedAppendQuery() ) ) {
1877 $appendQuery = "&" . $this->getFeedAppendQuery();
1882 foreach( $wgFeedClasses as $format => $class ) {
1883 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1890 * Generate a <link rel/> for an RSS feed.
1892 private function feedLink( $type, $url, $text ) {
1893 return Xml
::element( 'link', array(
1894 'rel' => 'alternate',
1895 'type' => "application/$type+xml",
1901 * Add a local or specified stylesheet, with the given media options.
1902 * Meant primarily for internal use...
1904 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1905 * @param $conditional -- for IE conditional comments, specifying an IE version
1906 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1908 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1911 $options['media'] = $media;
1913 $options['condition'] = $condition;
1915 $options['dir'] = $dir;
1916 $this->styles
[$style] = $options;
1918 public function addInlineStyle( $style_css ){
1919 $this->mScripts
.= "<style type=\"text/css\">$style_css</style>";
1922 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1923 * These will be applied to various media & IE conditionals.
1925 public function buildCssLinks() {
1927 foreach( $this->styles
as $file => $options ) {
1928 $link = $this->styleLink( $file, $options );
1933 return "\t" . implode( "\n\t", $links );
1936 protected function styleLink( $style, $options ) {
1939 if( isset( $options['dir'] ) ) {
1941 $siteDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1942 if( $siteDir != $options['dir'] )
1946 if( isset( $options['media'] ) ) {
1947 $media = $this->transformCssMedia( $options['media'] );
1948 if( is_null( $media ) ) {
1955 if( substr( $style, 0, 1 ) == '/' ||
1956 substr( $style, 0, 5 ) == 'http:' ||
1957 substr( $style, 0, 6 ) == 'https:' ) {
1960 global $wgStylePath, $wgStyleVersion;
1961 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1965 'rel' => 'stylesheet',
1967 'type' => 'text/css' );
1969 $attribs['media'] = $media;
1972 $link = Xml
::element( 'link', $attribs );
1974 if( isset( $options['condition'] ) ) {
1975 $condition = htmlspecialchars( $options['condition'] );
1976 $link = "<!--[if $condition]>$link<![endif]-->";
1981 function transformCssMedia( $media ) {
1982 global $wgRequest, $wgHandheldForIPhone;
1984 // Switch in on-screen display for media testing
1986 'printable' => 'print',
1987 'handheld' => 'handheld',
1989 foreach( $switches as $switch => $targetMedia ) {
1990 if( $wgRequest->getBool( $switch ) ) {
1991 if( $media == $targetMedia ) {
1993 } elseif( $media == 'screen' ) {
1999 // Expand longer media queries as iPhone doesn't grok 'handheld'
2000 if( $wgHandheldForIPhone ) {
2001 $mediaAliases = array(
2002 'screen' => 'screen and (min-device-width: 481px)',
2003 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2006 if( isset( $mediaAliases[$media] ) ) {
2007 $media = $mediaAliases[$media];
2015 * Turn off regular page output and return an error reponse
2016 * for when rate limiting has triggered.
2018 public function rateLimited() {
2020 $this->setPageTitle(wfMsg('actionthrottled'));
2021 $this->setRobotPolicy( 'noindex,follow' );
2022 $this->setArticleRelated( false );
2023 $this->enableClientCache( false );
2024 $this->mRedirect
= '';
2026 $this->setStatusCode(503);
2027 $this->addWikiMsg( 'actionthrottledtext' );
2029 $this->returnToMain( null, $this->getTitle() );
2033 * Show an "add new section" link?
2037 public function showNewSectionLink() {
2038 return $this->mNewSectionLink
;
2042 * Forcibly hide the new section link?
2046 public function forceHideNewSectionLink() {
2047 return $this->mHideNewSectionLink
;
2051 * Show a warning about slave lag
2053 * If the lag is higher than $wgSlaveLagCritical seconds,
2054 * then the warning is a bit more obvious. If the lag is
2055 * lower than $wgSlaveLagWarning, then no warning is shown.
2057 * @param int $lag Slave lag
2059 public function showLagWarning( $lag ) {
2060 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2061 if( $lag >= $wgSlaveLagWarning ) {
2062 $message = $lag < $wgSlaveLagCritical
2065 $warning = wfMsgExt( $message, 'parse', $lag );
2066 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2071 * Add a wikitext-formatted message to the output.
2072 * This is equivalent to:
2074 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2076 public function addWikiMsg( /*...*/ ) {
2077 $args = func_get_args();
2078 $name = array_shift( $args );
2079 $this->addWikiMsgArray( $name, $args );
2083 * Add a wikitext-formatted message to the output.
2084 * Like addWikiMsg() except the parameters are taken as an array
2085 * instead of a variable argument list.
2087 * $options is passed through to wfMsgExt(), see that function for details.
2089 public function addWikiMsgArray( $name, $args, $options = array() ) {
2090 $options[] = 'parse';
2091 $text = wfMsgExt( $name, $options, $args );
2092 $this->addHTML( $text );
2096 * This function takes a number of message/argument specifications, wraps them in
2097 * some overall structure, and then parses the result and adds it to the output.
2099 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2100 * on. The subsequent arguments may either be strings, in which case they are the
2101 * message names, or arrays, in which case the first element is the message name,
2102 * and subsequent elements are the parameters to that message.
2104 * The special named parameter 'options' in a message specification array is passed
2105 * through to the $options parameter of wfMsgExt().
2107 * Don't use this for messages that are not in users interface language.
2111 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2115 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2117 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2118 $msgSpecs = func_get_args();
2119 array_shift( $msgSpecs );
2120 $msgSpecs = array_values( $msgSpecs );
2122 foreach ( $msgSpecs as $n => $spec ) {
2124 if ( is_array( $spec ) ) {
2126 $name = array_shift( $args );
2127 if ( isset( $args['options'] ) ) {
2128 $options = $args['options'];
2129 unset( $args['options'] );
2135 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2137 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );