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(), $mCategories = array(), $mLanguageLinks = array();
17 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
18 var $mInlineMsg = array();
20 var $mTemplateIds = array();
23 var $mSuppressQuickbar = false;
24 var $mOnloadHandler = '';
25 var $mDoNothing = false;
26 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
27 var $mIsArticleRelated = true;
28 protected $mParserOptions = null; // lazy initialised, use parserOptions()
30 var $mFeedLinks = array();
32 var $mEnableClientCache = true;
33 var $mArticleBodyOnly = false;
35 var $mNewSectionLink = false;
36 var $mHideNewSectionLink = false;
37 var $mNoGallery = false;
38 var $mPageTitleActionText = '';
39 var $mParseWarnings = array();
40 var $mSquidMaxage = 0;
41 var $mRevisionId = null;
42 protected $mTitle = null;
45 * An array of stylesheet filenames (relative from skins path), with options
46 * for CSS media, IE conditions, and RTL/LTR direction.
47 * For internal use; add settings in the skin via $this->addStyle()
49 var $styles = array();
51 private $mIndexPolicy = 'index';
52 private $mFollowPolicy = 'follow';
53 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
58 * Initialise private variables
60 function __construct() {
61 global $wgAllowUserJs;
62 $this->mAllowUserJs
= $wgAllowUserJs;
65 public function redirect( $url, $responsecode = '302' ) {
66 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
67 $this->mRedirect
= str_replace( "\n", '', $url );
68 $this->mRedirectCode
= $responsecode;
71 public function getRedirect() {
72 return $this->mRedirect
;
76 * Set the HTTP status code to send with the output.
78 * @param int $statusCode
81 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
84 * Add a new <meta> tag
85 * To add an http-equiv meta tag, precede the name with "http:"
87 * @param $name tag name
88 * @param $val tag value
90 function addMeta( $name, $val ) {
91 array_push( $this->mMetatags
, array( $name, $val ) );
94 function addKeyword( $text ) {
95 if( is_array( $text )) {
96 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
98 array_push( $this->mKeywords
, $text );
101 function addScript( $script ) {
102 $this->mScripts
.= $script . "\n";
106 * Register and add a stylesheet from an extension directory.
107 * @param $url String path to sheet. Provide either a full url (beginning
108 * with 'http', etc) or a relative path from the document root
109 * (beginning with '/'). Otherwise it behaves identically to
110 * addStyle() and draws from the /skins folder.
112 public function addExtensionStyle( $url ) {
113 array_push( $this->mExtStyles
, $url );
117 * Add a JavaScript file out of skins/common, or a given relative path.
118 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
120 function addScriptFile( $file ) {
121 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
122 if( substr( $file, 0, 1 ) == '/' ) {
125 $path = "{$wgStylePath}/common/{$file}";
128 Xml
::element( 'script',
130 'type' => $wgJsMimeType,
131 'src' => "$path?$wgStyleVersion",
139 * Add a self-contained script tag with the given contents
140 * @param string $script JavaScript text, no <script> tags
142 function addInlineScript( $script ) {
143 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
147 * Get all registered JS and CSS tags for the header.
149 function getScript() {
150 return $this->mScripts
. $this->getHeadItems();
153 function getHeadItems() {
155 foreach ( $this->mHeadItems
as $item ) {
161 function addHeadItem( $name, $value ) {
162 $this->mHeadItems
[$name] = $value;
165 function hasHeadItem( $name ) {
166 return isset( $this->mHeadItems
[$name] );
169 function setETag($tag) { $this->mETag
= $tag; }
170 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
171 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
173 function addLink( $linkarr ) {
174 # $linkarr should be an associative array of attributes. We'll escape on output.
175 array_push( $this->mLinktags
, $linkarr );
178 # Get all links added by extensions
179 function getExtStyle() {
180 return $this->mExtStyles
;
183 function addMetadataLink( $linkarr ) {
184 # note: buggy CC software only reads first "meta" link
185 static $haveMeta = false;
186 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
187 $this->addLink( $linkarr );
192 * checkLastModified tells the client to use the client-cached page if
193 * possible. If sucessful, the OutputPage is disabled so that
194 * any future call to OutputPage->output() have no effect.
196 * Side effect: sets mLastModified for Last-Modified header
198 * @return bool True iff cache-ok headers was sent.
200 function checkLastModified( $timestamp ) {
201 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
203 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
204 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
207 if( !$wgCachePages ) {
208 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
211 if( $wgUser->getOption( 'nocache' ) ) {
212 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
216 $timestamp = wfTimestamp( TS_MW
, $timestamp );
217 $modifiedTimes = array(
218 'page' => $timestamp,
219 'user' => $wgUser->getTouched(),
220 'epoch' => $wgCacheEpoch
222 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
224 $maxModified = max( $modifiedTimes );
225 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
227 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
228 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
234 foreach ( $modifiedTimes as $name => $value ) {
235 if ( $info !== '' ) {
238 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
241 # IE sends sizes after the date like this:
242 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
243 # this breaks strtotime().
244 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
246 wfSuppressWarnings(); // E_STRICT system time bitching
247 $clientHeaderTime = strtotime( $clientHeader );
249 if ( !$clientHeaderTime ) {
250 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
253 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
255 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
256 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
257 wfDebug( __METHOD__
. ": effective Last-Modified: " .
258 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
259 if( $clientHeaderTime < $maxModified ) {
260 wfDebug( __METHOD__
. ": STALE, $info\n", false );
265 # Give a 304 response code and disable body output
266 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
267 ini_set('zlib.output_compression', 0);
268 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
269 $this->sendCacheControl();
272 // Don't output a compressed blob when using ob_gzhandler;
273 // it's technically against HTTP spec and seems to confuse
274 // Firefox when the response gets split over two packets.
275 wfClearOutputBuffers();
280 function setPageTitleActionText( $text ) {
281 $this->mPageTitleActionText
= $text;
284 function getPageTitleActionText () {
285 if ( isset( $this->mPageTitleActionText
) ) {
286 return $this->mPageTitleActionText
;
291 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
293 * @param $policy string The literal string to output as the contents of
294 * the meta tag. Will be parsed according to the spec and output in
298 public function setRobotPolicy( $policy ) {
299 $policy = Article
::formatRobotPolicy( $policy );
301 if( isset( $policy['index'] ) ){
302 $this->setIndexPolicy( $policy['index'] );
304 if( isset( $policy['follow'] ) ){
305 $this->setFollowPolicy( $policy['follow'] );
310 * Set the index policy for the page, but leave the follow policy un-
313 * @param $policy string Either 'index' or 'noindex'.
316 public function setIndexPolicy( $policy ) {
317 $policy = trim( $policy );
318 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
319 $this->mIndexPolicy
= $policy;
324 * Set the follow policy for the page, but leave the index policy un-
327 * @param $policy string Either 'follow' or 'nofollow'.
330 public function setFollowPolicy( $policy ) {
331 $policy = trim( $policy );
332 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
333 $this->mFollowPolicy
= $policy;
338 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
340 public function setHTMLTitle( $name ) {
341 $this->mHTMLtitle
= $name;
345 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
346 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
347 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
348 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
350 public function setPageTitle( $name ) {
353 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
354 # but leave "<i>foobar</i>" alone
355 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
356 $this->mPagetitle
= $nameWithTags;
358 $taction = $this->getPageTitleActionText();
359 if( !empty( $taction ) ) {
360 $name .= ' - '.$taction;
363 # change "<i>foo&bar</i>" to "foo&bar"
364 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
367 public function setTitle( $t ) {
371 public function getTitle() {
372 if ( $this->mTitle
instanceof Title
) {
373 return $this->mTitle
;
376 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
382 public function getHTMLTitle() { return $this->mHTMLtitle
; }
383 public function getPageTitle() { return $this->mPagetitle
; }
384 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
385 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
386 public function getSubtitle() { return $this->mSubtitle
; }
387 public function isArticle() { return $this->mIsarticle
; }
388 public function setPrintable() { $this->mPrintable
= true; }
389 public function isPrintable() { return $this->mPrintable
; }
390 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
391 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
392 public function getOnloadHandler() { return $this->mOnloadHandler
; }
393 public function disable() { $this->mDoNothing
= true; }
394 public function isDisabled() { return $this->mDoNothing
; }
396 public function setSyndicated( $show = true ) {
398 $this->setFeedAppendQuery( false );
400 $this->mFeedLinks
= array();
404 public function setFeedAppendQuery( $val ) {
405 global $wgFeedClasses, $wgAdvertisedFeedTypes;
407 $this->mFeedLinks
= array();
409 foreach ( $wgAdvertisedFeedTypes as $type ) {
410 $query = "feed=$type";
411 if ( is_string( $val ) ) {
412 $query .= '&' . $val;
414 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
418 public function addFeedLink( $format, $href ) {
419 $this->mFeedLinks
[$format] = $href;
422 public function isSyndicated() { return count($this->mFeedLinks
); }
424 public function setArticleRelated( $v ) {
425 $this->mIsArticleRelated
= $v;
427 $this->mIsarticle
= false;
430 public function setArticleFlag( $v ) {
431 $this->mIsarticle
= $v;
433 $this->mIsArticleRelated
= $v;
437 public function isArticleRelated() { return $this->mIsArticleRelated
; }
439 public function getLanguageLinks() { return $this->mLanguageLinks
; }
440 public function addLanguageLinks($newLinkArray) {
441 $this->mLanguageLinks +
= $newLinkArray;
443 public function setLanguageLinks($newLinkArray) {
444 $this->mLanguageLinks
= $newLinkArray;
447 public function getCategoryLinks() {
448 return $this->mCategoryLinks
;
451 public function getCategories() {
452 return $this->mCategories
;
456 * Add an array of categories, with names in the keys
458 public function addCategoryLinks( $categories ) {
459 global $wgUser, $wgContLang;
461 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
465 # Add the links to a LinkBatch
466 $arr = array( NS_CATEGORY
=> $categories );
468 $lb->setArray( $arr );
470 # Fetch existence plus the hiddencat property
471 $dbr = wfGetDB( DB_SLAVE
);
472 $pageTable = $dbr->tableName( 'page' );
473 $where = $lb->constructSet( 'page', $dbr );
474 $propsTable = $dbr->tableName( 'page_props' );
475 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
476 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
477 $res = $dbr->query( $sql, __METHOD__
);
479 # Add the results to the link cache
480 $lb->addResultToCache( LinkCache
::singleton(), $res );
482 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
483 $categories = array_combine( array_keys( $categories ),
484 array_fill( 0, count( $categories ), 'normal' ) );
486 # Mark hidden categories
487 foreach ( $res as $row ) {
488 if ( isset( $row->pp_value
) ) {
489 $categories[$row->page_title
] = 'hidden';
493 # Add the remaining categories to the skin
494 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
495 $sk = $wgUser->getSkin();
496 foreach ( $categories as $category => $type ) {
497 $origcategory = $category;
498 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
499 $wgContLang->findVariantLink( $category, $title, true );
500 if ( $category != $origcategory )
501 if ( array_key_exists( $category, $categories ) )
503 $text = $wgContLang->convertHtml( $title->getText() );
504 $this->mCategories
[] = $title->getText();
505 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
510 public function setCategoryLinks($categories) {
511 $this->mCategoryLinks
= array();
512 $this->addCategoryLinks($categories);
515 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
516 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
518 public function disallowUserJs() { $this->mAllowUserJs
= false; }
519 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
521 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
522 public function addHTML( $text ) { $this->mBodytext
.= $text; }
523 public function clearHTML() { $this->mBodytext
= ''; }
524 public function getHTML() { return $this->mBodytext
; }
525 public function debug( $text ) { $this->mDebugtext
.= $text; }
528 public function setParserOptions( $options ) {
529 wfDeprecated( __METHOD__
);
530 return $this->parserOptions( $options );
533 public function parserOptions( $options = null ) {
534 if ( !$this->mParserOptions
) {
535 $this->mParserOptions
= new ParserOptions
;
537 return wfSetVar( $this->mParserOptions
, $options );
541 * Set the revision ID which will be seen by the wiki text parser
542 * for things such as embedded {{REVISIONID}} variable use.
543 * @param mixed $revid an integer, or NULL
544 * @return mixed previous value
546 public function setRevisionId( $revid ) {
547 $val = is_null( $revid ) ?
null : intval( $revid );
548 return wfSetVar( $this->mRevisionId
, $val );
551 public function getRevisionId() {
552 return $this->mRevisionId
;
556 * Convert wikitext to HTML and add it to the buffer
557 * Default assumes that the current page title will
560 * @param string $text
561 * @param bool $linestart
563 public function addWikiText( $text, $linestart = true ) {
564 $title = $this->getTitle(); // Work arround E_STRICT
565 $this->addWikiTextTitle( $text, $title, $linestart );
568 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
569 $this->addWikiTextTitle($text, $title, $linestart);
572 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
573 $this->addWikiTextTitle( $text, $title, $linestart, true );
576 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
579 wfProfileIn( __METHOD__
);
581 wfIncrStats( 'pcache_not_possible' );
583 $popts = $this->parserOptions();
584 $oldTidy = $popts->setTidy( $tidy );
586 $parserOutput = $wgParser->parse( $text, $title, $popts,
587 $linestart, true, $this->mRevisionId
);
589 $popts->setTidy( $oldTidy );
591 $this->addParserOutput( $parserOutput );
593 wfProfileOut( __METHOD__
);
598 * @param ParserOutput object &$parserOutput
600 public function addParserOutputNoText( &$parserOutput ) {
601 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
603 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
604 $this->addCategoryLinks( $parserOutput->getCategories() );
605 $this->mNewSectionLink
= $parserOutput->getNewSection();
606 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
608 $this->mParseWarnings
= $parserOutput->getWarnings();
609 if ( $parserOutput->getCacheTime() == -1 ) {
610 $this->enableClientCache( false );
612 $this->mNoGallery
= $parserOutput->getNoGallery();
613 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
615 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
616 if ( isset( $this->mTemplateIds
[$ns] ) ) {
617 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
619 $this->mTemplateIds
[$ns] = $dbks;
623 $dt = $parserOutput->getDisplayTitle();
624 $title = $parserOutput->getTitleText();
625 if ( $dt !== false ) {
626 $this->setPageTitle( $dt );
628 else if ( $title != '' ) {
629 $this->setPageTitle( $title );
632 // Hooks registered in the object
633 global $wgParserOutputHooks;
634 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
635 list( $hookName, $data ) = $hookInfo;
636 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
637 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
641 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
646 * @param ParserOutput &$parserOutput
648 function addParserOutput( &$parserOutput ) {
649 $this->addParserOutputNoText( $parserOutput );
650 $text = $parserOutput->getText();
651 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
652 $this->addHTML( $text );
656 * Add wikitext to the buffer, assuming that this is the primary text for a page view
657 * Saves the text into the parser cache if possible.
659 * @param string $text
660 * @param Article $article
662 * @deprecated Use Article::outputWikitext
664 public function addPrimaryWikiText( $text, $article, $cache = true ) {
667 wfDeprecated( __METHOD__
);
669 $popts = $this->parserOptions();
670 $popts->setTidy(true);
671 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
672 $popts, true, true, $this->mRevisionId
);
673 $popts->setTidy(false);
674 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
675 $parserCache = ParserCache
::singleton();
676 $parserCache->save( $parserOutput, $article, $popts);
679 $this->addParserOutput( $parserOutput );
683 * @deprecated use addWikiTextTidy()
685 public function addSecondaryWikiText( $text, $linestart = true ) {
686 wfDeprecated( __METHOD__
);
687 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
691 * Add wikitext with tidy enabled
693 public function addWikiTextTidy( $text, $linestart = true ) {
694 $title = $this->getTitle();
695 $this->addWikiTextTitleTidy($text, $title, $linestart);
700 * Add the output of a QuickTemplate to the output buffer
702 * @param QuickTemplate $template
704 public function addTemplate( &$template ) {
706 $template->execute();
707 $this->addHTML( ob_get_contents() );
712 * Parse wikitext and return the HTML.
714 * @param string $text
715 * @param bool $linestart Is this the start of a line?
716 * @param bool $interface ??
718 public function parse( $text, $linestart = true, $interface = false ) {
720 if( is_null( $this->getTitle() ) ) {
721 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
723 $popts = $this->parserOptions();
724 if ( $interface) { $popts->setInterfaceMessage(true); }
725 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
726 $linestart, true, $this->mRevisionId
);
727 if ( $interface) { $popts->setInterfaceMessage(false); }
728 return $parserOutput->getText();
731 /** Parse wikitext, strip paragraphs, and return the HTML. */
732 public function parseInline( $text, $linestart = true, $interface = false ) {
733 $parsed = $this->parse( $text, $linestart, $interface );
736 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
744 * @param Article $article
749 * @return bool True if successful, else false.
751 public function tryParserCache( &$article ) {
752 wfDeprecated( __METHOD__
);
753 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
755 if ($parserOutput !== false) {
756 $this->addParserOutput( $parserOutput );
764 * @param int $maxage Maximum cache time on the Squid, in seconds.
766 public function setSquidMaxage( $maxage ) {
767 $this->mSquidMaxage
= $maxage;
771 * Use enableClientCache(false) to force it to send nocache headers
774 public function enableClientCache( $state ) {
775 return wfSetVar( $this->mEnableClientCache
, $state );
778 function getCacheVaryCookies() {
779 global $wgCookiePrefix, $wgCacheVaryCookies;
781 if ( $cookies === null ) {
782 $cookies = array_merge(
784 "{$wgCookiePrefix}Token",
785 "{$wgCookiePrefix}LoggedOut",
790 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
795 function uncacheableBecauseRequestVars() {
797 return $wgRequest->getText('useskin', false) === false
798 && $wgRequest->getText('uselang', false) === false;
802 * Check if the request has a cache-varying cookie header
803 * If it does, it's very important that we don't allow public caching
805 function haveCacheVaryCookies() {
807 $cookieHeader = $wgRequest->getHeader( 'cookie' );
808 if ( $cookieHeader === false ) {
811 $cvCookies = $this->getCacheVaryCookies();
812 foreach ( $cvCookies as $cookieName ) {
813 # Check for a simple string match, like the way squid does it
814 if ( strpos( $cookieHeader, $cookieName ) ) {
815 wfDebug( __METHOD__
.": found $cookieName\n" );
819 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
823 public function addVaryHeader( $header, $option = null ) {
824 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
825 $this->mVaryHeader
[$header] = $option;
827 elseif( is_array( $option ) ) {
828 if( is_array( $this->mVaryHeader
[$header] ) ) {
829 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
832 $this->mVaryHeader
[$header] = $option;
835 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
838 /** Get a complete X-Vary-Options header */
839 public function getXVO() {
840 $cvCookies = $this->getCacheVaryCookies();
842 $cookiesOption = array();
843 foreach ( $cvCookies as $cookieName ) {
844 $cookiesOption[] = 'string-contains=' . $cookieName;
846 $this->addVaryHeader( 'Cookie', $cookiesOption );
849 foreach( $this->mVaryHeader
as $header => $option ) {
850 $newheader = $header;
851 if( is_array( $option ) )
852 $newheader .= ';' . implode( ';', $option );
853 $headers[] = $newheader;
855 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
860 /** bug 21672: Add Accept-Language to Vary and XVO headers
861 if there's no 'variant' parameter existed in GET.
864 /w/index.php?title=Main_page should always be served; but
865 /w/index.php?title=Main_page&variant=zh-cn should never be served.
867 patched by Liangent and Philip */
868 function addAcceptLanguage() {
869 global $wgRequest, $wgContLang;
870 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
871 $variants = $wgContLang->getVariants();
873 foreach ( $variants as $variant ) {
874 if( $variant === $wgContLang->getCode() )
877 $aloption[] = "string-contains=$variant";
879 $this->addVaryHeader( 'Accept-Language', $aloption );
883 public function sendCacheControl() {
884 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
886 $response = $wgRequest->response();
887 if ($wgUseETag && $this->mETag
)
888 $response->header("ETag: $this->mETag");
890 $this->addAcceptLanguage();
892 # don't serve compressed data to clients who can't handle it
893 # maintain different caches for logged-in users and non-logged in ones
894 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
897 # Add an X-Vary-Options header for Squid with Wikimedia patches
898 $response->header( $this->getXVO() );
901 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
902 if( $wgUseSquid && session_id() == '' &&
903 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
906 # We'll purge the proxy cache explicitly, but require end user agents
907 # to revalidate against the proxy on each visit.
908 # Surrogate-Control controls our Squid, Cache-Control downstream caches
909 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
910 # start with a shorter timeout for initial testing
911 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
912 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
913 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
915 # We'll purge the proxy cache for anons explicitly, but require end user agents
916 # to revalidate against the proxy on each visit.
917 # IMPORTANT! The Squid needs to replace the Cache-Control header with
918 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
919 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
920 # start with a shorter timeout for initial testing
921 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
922 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
925 # We do want clients to cache if they can, but they *must* check for updates
926 # on revisiting the page.
927 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
928 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
929 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
931 if($this->mLastModified
) {
932 $response->header( "Last-Modified: {$this->mLastModified}" );
935 wfDebug( __METHOD__
. ": no caching **\n", false );
937 # In general, the absence of a last modified header should be enough to prevent
938 # the client from using its cache. We send a few other things just to make sure.
939 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
940 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
941 $response->header( 'Pragma: no-cache' );
943 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
947 * Get the message associed with the HTTP response code $code
949 * @param $code Integer: status code
950 * @return String or null: message or null if $code is not in the list of
953 public static function getStatusMessage( $code ) {
954 static $statusMessage = array(
956 101 => 'Switching Protocols',
961 203 => 'Non-Authoritative Information',
963 205 => 'Reset Content',
964 206 => 'Partial Content',
965 207 => 'Multi-Status',
966 300 => 'Multiple Choices',
967 301 => 'Moved Permanently',
970 304 => 'Not Modified',
972 307 => 'Temporary Redirect',
973 400 => 'Bad Request',
974 401 => 'Unauthorized',
975 402 => 'Payment Required',
978 405 => 'Method Not Allowed',
979 406 => 'Not Acceptable',
980 407 => 'Proxy Authentication Required',
981 408 => 'Request Timeout',
984 411 => 'Length Required',
985 412 => 'Precondition Failed',
986 413 => 'Request Entity Too Large',
987 414 => 'Request-URI Too Large',
988 415 => 'Unsupported Media Type',
989 416 => 'Request Range Not Satisfiable',
990 417 => 'Expectation Failed',
991 422 => 'Unprocessable Entity',
993 424 => 'Failed Dependency',
994 500 => 'Internal Server Error',
995 501 => 'Not Implemented',
996 502 => 'Bad Gateway',
997 503 => 'Service Unavailable',
998 504 => 'Gateway Timeout',
999 505 => 'HTTP Version Not Supported',
1000 507 => 'Insufficient Storage'
1002 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1006 * Finally, all the text has been munged and accumulated into
1007 * the object, let's actually output it:
1009 public function output() {
1010 global $wgUser, $wgOutputEncoding, $wgRequest;
1011 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1012 global $wgUseAjax, $wgAjaxWatch;
1013 global $wgEnableMWSuggest, $wgUniversalEditButton;
1016 if( $this->mDoNothing
){
1019 wfProfileIn( __METHOD__
);
1020 if ( $this->mRedirect
!= '' ) {
1021 # Standards require redirect URLs to be absolute
1022 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1023 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1024 if( !$wgDebugRedirects ) {
1025 $message = self
::getStatusMessage( $this->mRedirectCode
);
1026 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1028 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1030 $this->sendCacheControl();
1032 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1033 if( $wgDebugRedirects ) {
1034 $url = htmlspecialchars( $this->mRedirect
);
1035 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1036 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1037 print "</body>\n</html>\n";
1039 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1041 wfProfileOut( __METHOD__
);
1043 } elseif ( $this->mStatusCode
) {
1044 $message = self
::getStatusMessage( $this->mStatusCode
);
1046 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1049 $sk = $wgUser->getSkin();
1052 $this->addScriptFile( 'ajax.js' );
1054 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1056 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1057 $this->addScriptFile( 'ajaxwatch.js' );
1060 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1061 $this->addScriptFile( 'mwsuggest.js' );
1065 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1066 $this->addScriptFile( 'rightclickedit.js' );
1069 if( $wgUniversalEditButton ) {
1070 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1071 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1072 // Original UniversalEditButton
1073 $msg = wfMsg('edit');
1074 $this->addLink( array(
1075 'rel' => 'alternate',
1076 'type' => 'application/x-wiki',
1078 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1080 // Alternate edit link
1081 $this->addLink( array(
1084 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1089 # Buffer output; final headers may depend on later processing
1092 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1093 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1095 if ($this->mArticleBodyOnly
) {
1096 $this->out($this->mBodytext
);
1098 // Hook that allows last minute changes to the output page, e.g.
1099 // adding of CSS or Javascript by extensions.
1100 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1102 wfProfileIn( 'Output-skin' );
1103 $sk->outputPage( $this );
1104 wfProfileOut( 'Output-skin' );
1107 $this->sendCacheControl();
1109 wfProfileOut( __METHOD__
);
1113 * Actually output something with print(). Performs an iconv to the
1114 * output encoding, if needed.
1115 * @param string $ins The string to output
1117 public function out( $ins ) {
1118 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1119 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1122 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1123 if ( false === $outs ) { $outs = $ins; }
1131 public static function setEncodings() {
1132 global $wgInputEncoding, $wgOutputEncoding;
1135 $wgInputEncoding = strtolower( $wgInputEncoding );
1137 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1138 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1141 $wgOutputEncoding = $wgInputEncoding;
1145 * Deprecated, use wfReportTime() instead.
1149 public function reportTime() {
1150 wfDeprecated( __METHOD__
);
1151 $time = wfReportTime();
1156 * Produce a "user is blocked" page.
1158 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1161 function blockedPage( $return = true ) {
1162 global $wgUser, $wgContLang, $wgLang;
1164 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1165 $this->setRobotPolicy( 'noindex,nofollow' );
1166 $this->setArticleRelated( false );
1168 $name = User
::whoIs( $wgUser->blockedBy() );
1169 $reason = $wgUser->blockedFor();
1170 if( $reason == '' ) {
1171 $reason = wfMsg( 'blockednoreason' );
1173 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1176 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1178 $blockid = $wgUser->mBlock
->mId
;
1180 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1181 if ( $blockExpiry == 'infinity' ) {
1182 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1183 // Search for localization in 'ipboptions'
1184 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1185 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1186 if ( strpos( $option, ":" ) === false )
1188 list( $show, $value ) = explode( ":", $option );
1189 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1190 $blockExpiry = $show;
1195 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1198 if ( $wgUser->mBlock
->mAuto
) {
1199 $msg = 'autoblockedtext';
1201 $msg = 'blockedtext';
1204 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1205 * This could be a username, an ip range, or a single ip. */
1206 $intended = $wgUser->mBlock
->mAddress
;
1208 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1210 # Don't auto-return to special pages
1212 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1213 $this->returnToMain( null, $return );
1218 * Output a standard error page
1220 * @param string $title Message key for page title
1221 * @param string $msg Message key for page text
1222 * @param array $params Message parameters
1224 public function showErrorPage( $title, $msg, $params = array() ) {
1225 if ( $this->getTitle() ) {
1226 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1228 $this->setPageTitle( wfMsg( $title ) );
1229 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1230 $this->setRobotPolicy( 'noindex,nofollow' );
1231 $this->setArticleRelated( false );
1232 $this->enableClientCache( false );
1233 $this->mRedirect
= '';
1234 $this->mBodytext
= '';
1236 array_unshift( $params, 'parse' );
1237 array_unshift( $params, $msg );
1238 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1240 $this->returnToMain();
1244 * Output a standard permission error page
1246 * @param array $errors Error message keys
1248 public function showPermissionsErrorPage( $errors, $action = null )
1250 $this->mDebugtext
.= 'Original title: ' .
1251 $this->getTitle()->getPrefixedText() . "\n";
1252 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1253 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1254 $this->setRobotPolicy( 'noindex,nofollow' );
1255 $this->setArticleRelated( false );
1256 $this->enableClientCache( false );
1257 $this->mRedirect
= '';
1258 $this->mBodytext
= '';
1259 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1263 public function errorpage( $title, $msg ) {
1264 wfDeprecated( __METHOD__
);
1265 throw new ErrorPageError( $title, $msg );
1269 * Display an error page indicating that a given version of MediaWiki is
1270 * required to use it
1272 * @param mixed $version The version of MediaWiki needed to use the page
1274 public function versionRequired( $version ) {
1275 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1276 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1277 $this->setRobotPolicy( 'noindex,nofollow' );
1278 $this->setArticleRelated( false );
1279 $this->mBodytext
= '';
1281 $this->addWikiMsg( 'versionrequiredtext', $version );
1282 $this->returnToMain();
1286 * Display an error page noting that a given permission bit is required.
1288 * @param string $permission key required
1290 public function permissionRequired( $permission ) {
1293 $this->setPageTitle( wfMsg( 'badaccess' ) );
1294 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1295 $this->setRobotPolicy( 'noindex,nofollow' );
1296 $this->setArticleRelated( false );
1297 $this->mBodytext
= '';
1299 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1300 User
::getGroupsWithPermission( $permission ) );
1302 $this->addWikiMsg( 'badaccess-groups',
1303 $wgLang->commaList( $groups ),
1306 $this->addWikiMsg( 'badaccess-group0' );
1308 $this->returnToMain();
1312 * Use permissionRequired.
1315 public function sysopRequired() {
1316 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1320 * Use permissionRequired.
1323 public function developerRequired() {
1324 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1328 * Produce the stock "please login to use the wiki" page
1330 public function loginToUse() {
1331 global $wgUser, $wgContLang;
1333 if( $wgUser->isLoggedIn() ) {
1334 $this->permissionRequired( 'read' );
1338 $skin = $wgUser->getSkin();
1340 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1341 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1342 $this->setRobotPolicy( 'noindex,nofollow' );
1343 $this->setArticleFlag( false );
1345 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1346 $loginLink = $skin->link(
1348 wfMsgHtml( 'loginreqlink' ),
1350 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1351 array( 'known', 'noclasses' )
1353 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1354 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1356 # Don't return to the main page if the user can't read it
1357 # otherwise we'll end up in a pointless loop
1358 $mainPage = Title
::newMainPage();
1359 if( $mainPage->userCanRead() )
1360 $this->returnToMain( null, $mainPage );
1364 public function databaseError( $fname, $sql, $error, $errno ) {
1365 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1369 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1370 * @return string The wikitext error-messages, formatted into a list.
1372 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1373 if ($action == null) {
1374 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1377 $action_desc = wfMsgNoTrans( "action-$action" );
1378 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1381 if (count( $errors ) > 1) {
1382 $text .= '<ul class="permissions-errors">' . "\n";
1384 foreach( $errors as $error )
1387 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1392 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1399 * Display a page stating that the Wiki is in read-only mode,
1400 * and optionally show the source of the page that the user
1401 * was trying to edit. Should only be called (for this
1402 * purpose) after wfReadOnly() has returned true.
1404 * For historical reasons, this function is _also_ used to
1405 * show the error message when a user tries to edit a page
1406 * they are not allowed to edit. (Unless it's because they're
1407 * blocked, then we show blockedPage() instead.) In this
1408 * case, the second parameter should be set to true and a list
1409 * of reasons supplied as the third parameter.
1411 * @todo Needs to be split into multiple functions.
1413 * @param string $source Source code to show (or null).
1414 * @param bool $protected Is this a permissions error?
1415 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1417 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1419 $skin = $wgUser->getSkin();
1421 $this->setRobotPolicy( 'noindex,nofollow' );
1422 $this->setArticleRelated( false );
1424 // If no reason is given, just supply a default "I can't let you do
1425 // that, Dave" message. Should only occur if called by legacy code.
1426 if ( $protected && empty($reasons) ) {
1427 $reasons[] = array( 'badaccess-group0' );
1430 if ( !empty($reasons) ) {
1431 // Permissions error
1433 $this->setPageTitle( wfMsg( 'viewsource' ) );
1442 array( 'known', 'noclasses' )
1447 $this->setPageTitle( wfMsg( 'badaccess' ) );
1449 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1451 // Wiki is read only
1452 $this->setPageTitle( wfMsg( 'readonly' ) );
1453 $reason = wfReadOnlyReason();
1454 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1457 // Show source, if supplied
1458 if( is_string( $source ) ) {
1459 $this->addWikiMsg( 'viewsourcetext' );
1462 'id' => 'wpTextbox1',
1463 'name' => 'wpTextbox1',
1464 'cols' => $wgUser->getOption( 'cols' ),
1465 'rows' => $wgUser->getOption( 'rows' ),
1466 'readonly' => 'readonly'
1468 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1470 // Show templates used by this article
1471 $skin = $wgUser->getSkin();
1472 $article = new Article( $this->getTitle() );
1473 $this->addHTML( "<div class='templatesUsed'>
1474 {$skin->formatTemplates( $article->getUsedTemplates() )}
1479 # If the title doesn't exist, it's fairly pointless to print a return
1480 # link to it. After all, you just tried editing it and couldn't, so
1481 # what's there to do there?
1482 if( $this->getTitle()->exists() ) {
1483 $this->returnToMain( null, $this->getTitle() );
1488 public function fatalError( $message ) {
1489 wfDeprecated( __METHOD__
);
1490 throw new FatalError( $message );
1494 public function unexpectedValueError( $name, $val ) {
1495 wfDeprecated( __METHOD__
);
1496 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1500 public function fileCopyError( $old, $new ) {
1501 wfDeprecated( __METHOD__
);
1502 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1506 public function fileRenameError( $old, $new ) {
1507 wfDeprecated( __METHOD__
);
1508 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1512 public function fileDeleteError( $name ) {
1513 wfDeprecated( __METHOD__
);
1514 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1518 public function fileNotFoundError( $name ) {
1519 wfDeprecated( __METHOD__
);
1520 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1523 public function showFatalError( $message ) {
1524 $this->setPageTitle( wfMsg( "internalerror" ) );
1525 $this->setRobotPolicy( "noindex,nofollow" );
1526 $this->setArticleRelated( false );
1527 $this->enableClientCache( false );
1528 $this->mRedirect
= '';
1529 $this->mBodytext
= $message;
1532 public function showUnexpectedValueError( $name, $val ) {
1533 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1536 public function showFileCopyError( $old, $new ) {
1537 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1540 public function showFileRenameError( $old, $new ) {
1541 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1544 public function showFileDeleteError( $name ) {
1545 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1548 public function showFileNotFoundError( $name ) {
1549 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1553 * Add a "return to" link pointing to a specified title
1555 * @param $title Title to link
1556 * @param $query String: query string
1558 public function addReturnTo( $title, $query = array() ) {
1560 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1561 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1562 $title, null, array(), $query ) );
1563 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1567 * Add a "return to" link pointing to a specified title,
1568 * or the title indicated in the request, or else the main page
1570 * @param $unused No longer used
1571 * @param $returnto Title or String to return to
1572 * @param $returntoquery String: query string for the return to link
1574 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1577 if ( $returnto == null ) {
1578 $returnto = $wgRequest->getText( 'returnto' );
1581 if ( $returntoquery == null ) {
1582 $returntoquery = $wgRequest->getText( 'returntoquery' );
1585 if ( $returnto === '' ) {
1586 $returnto = Title
::newMainPage();
1589 if ( is_object( $returnto ) ) {
1590 $titleObj = $returnto;
1592 $titleObj = Title
::newFromText( $returnto );
1594 if ( !is_object( $titleObj ) ) {
1595 $titleObj = Title
::newMainPage();
1598 $this->addReturnTo( $titleObj, $returntoquery );
1602 * @return string The doctype, opening <html>, and head element.
1604 * @param $sk Skin The given Skin
1606 public function headElement( Skin
$sk, $includeStyle = true ) {
1607 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1608 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1609 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1611 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1612 if ( $sk->commonPrintStylesheet() ) {
1613 $this->addStyle( 'common/wikiprintable.css', 'print' );
1615 $sk->setupUserCss( $this );
1619 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1620 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1623 if ( $this->getHTMLTitle() == '' ) {
1624 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1627 $dir = $wgContLang->getDir();
1630 if ( $wgWellFormedXml ) {
1631 # Unknown elements and attributes are okay in XML, but unknown
1632 # named entities are well-formedness errors and will break XML
1633 # parsers. Thus we need a doctype that gives us appropriate
1634 # entity definitions. The HTML5 spec permits four legacy
1635 # doctypes as obsolete but conforming, so let's pick one of
1636 # those, although it makes our pages look like XHTML1 Strict.
1637 # Isn't compatibility great?
1638 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1641 $ret .= "<!doctype html>\n";
1643 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1644 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1647 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1648 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1649 foreach($wgXhtmlNamespaces as $tag => $ns) {
1650 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1652 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1656 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1657 $ret .= implode( "\n", array(
1658 $this->getHeadLinks(),
1659 $this->buildCssLinks(),
1660 $this->getHeadScripts( $sk ),
1661 $this->getHeadItems(),
1664 $ret .= Html
::inlineStyle( $sk->usercss
);
1667 if ($wgUseTrackbacks && $this->isArticleRelated())
1668 $ret .= $this->getTitle()->trackbackRDF();
1670 $ret .= "</head>\n";
1675 * gets the global variables and mScripts
1677 * also adds userjs to the end if enabled:
1679 function getHeadScripts( Skin
$sk ) {
1680 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1681 global $wgStylePath, $wgStyleVersion;
1683 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1684 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1686 //add site JS if enabled:
1687 if( $wgUseSiteJs ) {
1688 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1689 $this->addScriptFile( Skin
::makeUrl( '-',
1690 "action=raw$jsCache&gen=js&useskin=" .
1691 urlencode( $sk->getSkinName() )
1696 //add user js if enabled:
1697 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1698 $action = $wgRequest->getVal( 'action', 'view' );
1699 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1700 # XXX: additional security check/prompt?
1701 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1703 $userpage = $wgUser->getUserPage();
1704 $userjs = Skin
::makeUrl(
1705 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1706 'action=raw&ctype=' . $wgJsMimeType );
1707 $this->addScriptFile( $userjs );
1711 $scripts .= "\n" . $this->mScripts
;
1715 protected function addDefaultMeta() {
1716 global $wgVersion, $wgHtml5;
1718 static $called = false;
1720 # Don't run this twice
1726 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1728 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1730 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1731 if( $p !== 'index,follow' ) {
1732 // http://www.robotstxt.org/wc/meta-user.html
1733 // Only show if it's different from the default robots policy
1734 $this->addMeta( 'robots', $p );
1737 if ( count( $this->mKeywords
) > 0 ) {
1739 "/<.*?" . ">/" => '',
1742 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1747 * @return string HTML tag links to be put in the header.
1749 public function getHeadLinks() {
1750 global $wgRequest, $wgFeed;
1752 // Ideally this should happen earlier, somewhere. :P
1753 $this->addDefaultMeta();
1757 foreach ( $this->mMetatags
as $tag ) {
1758 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1760 $tag[0] = substr( $tag[0], 5 );
1764 $tags[] = Html
::element( 'meta',
1767 'content' => $tag[1] ) );
1769 foreach ( $this->mLinktags
as $tag ) {
1770 $tags[] = Html
::element( 'link', $tag );
1774 foreach( $this->getSyndicationLinks() as $format => $link ) {
1775 # Use the page name for the title (accessed through $wgTitle since
1776 # there's no other way). In principle, this could lead to issues
1777 # with having the same name for different feeds corresponding to
1778 # the same page, but we can't avoid that at this low a level.
1780 $tags[] = $this->feedLink(
1783 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1784 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1787 # Recent changes feed should appear on every page (except recentchanges,
1788 # that would be redundant). Put it after the per-page feed to avoid
1789 # changing existing behavior. It's still available, probably via a
1790 # menu in your browser. Some sites might have a different feed they'd
1791 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1792 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1793 # If so, use it instead.
1795 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses, $wgAdvertisedFeedTypes;
1796 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1798 if ( $wgOverrideSiteFeed ) {
1799 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1800 $tags[] = $this->feedLink (
1802 htmlspecialchars( $feedUrl ),
1803 wfMsg( "site-{$type}-feed", $wgSitename ) );
1805 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1806 foreach ( $wgAdvertisedFeedTypes as $format ) {
1807 $tags[] = $this->feedLink(
1809 $rctitle->getLocalURL( "feed={$format}" ),
1810 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1815 return implode( "\n", $tags );
1819 * Return URLs for each supported syndication format for this page.
1820 * @return array associating format keys with URLs
1822 public function getSyndicationLinks() {
1823 return $this->mFeedLinks
;
1827 * Generate a <link rel/> for an RSS feed.
1829 private function feedLink( $type, $url, $text ) {
1830 return Html
::element( 'link', array(
1831 'rel' => 'alternate',
1832 'type' => "application/$type+xml",
1838 * Add a local or specified stylesheet, with the given media options.
1839 * Meant primarily for internal use...
1841 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1842 * @param $conditional -- for IE conditional comments, specifying an IE version
1843 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1845 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1847 // Even though we expect the media type to be lowercase, but here we
1848 // force it to lowercase to be safe.
1850 $options['media'] = $media;
1852 $options['condition'] = $condition;
1854 $options['dir'] = $dir;
1855 $this->styles
[$style] = $options;
1859 * Adds inline CSS styles
1860 * @param $style_css Mixed: inline CSS
1862 public function addInlineStyle( $style_css ){
1863 $this->mScripts
.= Html
::inlineStyle( $style_css );
1867 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1868 * These will be applied to various media & IE conditionals.
1870 public function buildCssLinks() {
1872 foreach( $this->styles
as $file => $options ) {
1873 $link = $this->styleLink( $file, $options );
1878 return implode( "\n", $links );
1881 protected function styleLink( $style, $options ) {
1884 if( isset( $options['dir'] ) ) {
1886 $siteDir = $wgContLang->getDir();
1887 if( $siteDir != $options['dir'] )
1891 if( isset( $options['media'] ) ) {
1892 $media = $this->transformCssMedia( $options['media'] );
1893 if( is_null( $media ) ) {
1900 if( substr( $style, 0, 1 ) == '/' ||
1901 substr( $style, 0, 5 ) == 'http:' ||
1902 substr( $style, 0, 6 ) == 'https:' ) {
1905 global $wgStylePath, $wgStyleVersion;
1906 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1909 $link = Html
::linkedStyle( $url, $media );
1911 if( isset( $options['condition'] ) ) {
1912 $condition = htmlspecialchars( $options['condition'] );
1913 $link = "<!--[if $condition]>$link<![endif]-->";
1918 function transformCssMedia( $media ) {
1919 global $wgRequest, $wgHandheldForIPhone;
1921 // Switch in on-screen display for media testing
1923 'printable' => 'print',
1924 'handheld' => 'handheld',
1926 foreach( $switches as $switch => $targetMedia ) {
1927 if( $wgRequest->getBool( $switch ) ) {
1928 if( $media == $targetMedia ) {
1930 } elseif( $media == 'screen' ) {
1936 // Expand longer media queries as iPhone doesn't grok 'handheld'
1937 if( $wgHandheldForIPhone ) {
1938 $mediaAliases = array(
1939 'screen' => 'screen and (min-device-width: 481px)',
1940 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1943 if( isset( $mediaAliases[$media] ) ) {
1944 $media = $mediaAliases[$media];
1952 * Turn off regular page output and return an error reponse
1953 * for when rate limiting has triggered.
1955 public function rateLimited() {
1957 $this->setPageTitle(wfMsg('actionthrottled'));
1958 $this->setRobotPolicy( 'noindex,follow' );
1959 $this->setArticleRelated( false );
1960 $this->enableClientCache( false );
1961 $this->mRedirect
= '';
1963 $this->setStatusCode(503);
1964 $this->addWikiMsg( 'actionthrottledtext' );
1966 $this->returnToMain( null, $this->getTitle() );
1970 * Show an "add new section" link?
1974 public function showNewSectionLink() {
1975 return $this->mNewSectionLink
;
1979 * Forcibly hide the new section link?
1983 public function forceHideNewSectionLink() {
1984 return $this->mHideNewSectionLink
;
1988 * Show a warning about slave lag
1990 * If the lag is higher than $wgSlaveLagCritical seconds,
1991 * then the warning is a bit more obvious. If the lag is
1992 * lower than $wgSlaveLagWarning, then no warning is shown.
1994 * @param int $lag Slave lag
1996 public function showLagWarning( $lag ) {
1997 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
1998 if( $lag >= $wgSlaveLagWarning ) {
1999 $message = $lag < $wgSlaveLagCritical
2002 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2003 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2008 * Add a wikitext-formatted message to the output.
2009 * This is equivalent to:
2011 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2013 public function addWikiMsg( /*...*/ ) {
2014 $args = func_get_args();
2015 $name = array_shift( $args );
2016 $this->addWikiMsgArray( $name, $args );
2020 * Add a wikitext-formatted message to the output.
2021 * Like addWikiMsg() except the parameters are taken as an array
2022 * instead of a variable argument list.
2024 * $options is passed through to wfMsgExt(), see that function for details.
2026 public function addWikiMsgArray( $name, $args, $options = array() ) {
2027 $options[] = 'parse';
2028 $text = wfMsgExt( $name, $options, $args );
2029 $this->addHTML( $text );
2033 * This function takes a number of message/argument specifications, wraps them in
2034 * some overall structure, and then parses the result and adds it to the output.
2036 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2037 * on. The subsequent arguments may either be strings, in which case they are the
2038 * message names, or arrays, in which case the first element is the message name,
2039 * and subsequent elements are the parameters to that message.
2041 * The special named parameter 'options' in a message specification array is passed
2042 * through to the $options parameter of wfMsgExt().
2044 * Don't use this for messages that are not in users interface language.
2048 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2052 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2054 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2055 $msgSpecs = func_get_args();
2056 array_shift( $msgSpecs );
2057 $msgSpecs = array_values( $msgSpecs );
2059 foreach ( $msgSpecs as $n => $spec ) {
2061 if ( is_array( $spec ) ) {
2063 $name = array_shift( $args );
2064 if ( isset( $args['options'] ) ) {
2065 $options = $args['options'];
2066 unset( $args['options'] );
2072 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2074 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );