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;
407 $this->mFeedLinks
= array();
409 foreach( $wgFeedClasses as $type => $class ) {
410 $query = "feed=$type";
411 if ( is_string( $val ) )
412 $query .= '&' . $val;
413 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
417 public function addFeedLink( $format, $href ) {
418 $this->mFeedLinks
[$format] = $href;
421 public function isSyndicated() { return count($this->mFeedLinks
); }
423 public function setArticleRelated( $v ) {
424 $this->mIsArticleRelated
= $v;
426 $this->mIsarticle
= false;
429 public function setArticleFlag( $v ) {
430 $this->mIsarticle
= $v;
432 $this->mIsArticleRelated
= $v;
436 public function isArticleRelated() { return $this->mIsArticleRelated
; }
438 public function getLanguageLinks() { return $this->mLanguageLinks
; }
439 public function addLanguageLinks($newLinkArray) {
440 $this->mLanguageLinks +
= $newLinkArray;
442 public function setLanguageLinks($newLinkArray) {
443 $this->mLanguageLinks
= $newLinkArray;
446 public function getCategoryLinks() {
447 return $this->mCategoryLinks
;
450 public function getCategories() {
451 return $this->mCategories
;
455 * Add an array of categories, with names in the keys
457 public function addCategoryLinks( $categories ) {
458 global $wgUser, $wgContLang;
460 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
464 # Add the links to a LinkBatch
465 $arr = array( NS_CATEGORY
=> $categories );
467 $lb->setArray( $arr );
469 # Fetch existence plus the hiddencat property
470 $dbr = wfGetDB( DB_SLAVE
);
471 $pageTable = $dbr->tableName( 'page' );
472 $where = $lb->constructSet( 'page', $dbr );
473 $propsTable = $dbr->tableName( 'page_props' );
474 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
475 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
476 $res = $dbr->query( $sql, __METHOD__
);
478 # Add the results to the link cache
479 $lb->addResultToCache( LinkCache
::singleton(), $res );
481 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
482 $categories = array_combine( array_keys( $categories ),
483 array_fill( 0, count( $categories ), 'normal' ) );
485 # Mark hidden categories
486 foreach ( $res as $row ) {
487 if ( isset( $row->pp_value
) ) {
488 $categories[$row->page_title
] = 'hidden';
492 # Add the remaining categories to the skin
493 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
494 $sk = $wgUser->getSkin();
495 foreach ( $categories as $category => $type ) {
496 $origcategory = $category;
497 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
498 $wgContLang->findVariantLink( $category, $title, true );
499 if ( $category != $origcategory )
500 if ( array_key_exists( $category, $categories ) )
502 $text = $wgContLang->convertHtml( $title->getText() );
503 $this->mCategories
[] = $title->getText();
504 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
509 public function setCategoryLinks($categories) {
510 $this->mCategoryLinks
= array();
511 $this->addCategoryLinks($categories);
514 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
515 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
517 public function disallowUserJs() { $this->mAllowUserJs
= false; }
518 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
520 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
521 public function addHTML( $text ) { $this->mBodytext
.= $text; }
522 public function clearHTML() { $this->mBodytext
= ''; }
523 public function getHTML() { return $this->mBodytext
; }
524 public function debug( $text ) { $this->mDebugtext
.= $text; }
527 public function setParserOptions( $options ) {
528 wfDeprecated( __METHOD__
);
529 return $this->parserOptions( $options );
532 public function parserOptions( $options = null ) {
533 if ( !$this->mParserOptions
) {
534 $this->mParserOptions
= new ParserOptions
;
536 return wfSetVar( $this->mParserOptions
, $options );
540 * Set the revision ID which will be seen by the wiki text parser
541 * for things such as embedded {{REVISIONID}} variable use.
542 * @param mixed $revid an integer, or NULL
543 * @return mixed previous value
545 public function setRevisionId( $revid ) {
546 $val = is_null( $revid ) ?
null : intval( $revid );
547 return wfSetVar( $this->mRevisionId
, $val );
550 public function getRevisionId() {
551 return $this->mRevisionId
;
555 * Convert wikitext to HTML and add it to the buffer
556 * Default assumes that the current page title will
559 * @param string $text
560 * @param bool $linestart
562 public function addWikiText( $text, $linestart = true ) {
563 $title = $this->getTitle(); // Work arround E_STRICT
564 $this->addWikiTextTitle( $text, $title, $linestart );
567 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
568 $this->addWikiTextTitle($text, $title, $linestart);
571 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
572 $this->addWikiTextTitle( $text, $title, $linestart, true );
575 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
578 wfProfileIn( __METHOD__
);
580 wfIncrStats( 'pcache_not_possible' );
582 $popts = $this->parserOptions();
583 $oldTidy = $popts->setTidy( $tidy );
585 $parserOutput = $wgParser->parse( $text, $title, $popts,
586 $linestart, true, $this->mRevisionId
);
588 $popts->setTidy( $oldTidy );
590 $this->addParserOutput( $parserOutput );
592 wfProfileOut( __METHOD__
);
597 * @param ParserOutput object &$parserOutput
599 public function addParserOutputNoText( &$parserOutput ) {
600 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
602 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
603 $this->addCategoryLinks( $parserOutput->getCategories() );
604 $this->mNewSectionLink
= $parserOutput->getNewSection();
605 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
607 $this->mParseWarnings
= $parserOutput->getWarnings();
608 if ( $parserOutput->getCacheTime() == -1 ) {
609 $this->enableClientCache( false );
611 $this->mNoGallery
= $parserOutput->getNoGallery();
612 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
614 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
615 if ( isset( $this->mTemplateIds
[$ns] ) ) {
616 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
618 $this->mTemplateIds
[$ns] = $dbks;
622 $dt = $parserOutput->getDisplayTitle();
623 $title = $parserOutput->getTitleText();
624 if ( $dt !== false ) {
625 $this->setPageTitle( $dt );
627 else if ( $title != '' ) {
628 $this->setPageTitle( $title );
631 // Hooks registered in the object
632 global $wgParserOutputHooks;
633 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
634 list( $hookName, $data ) = $hookInfo;
635 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
636 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
640 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
645 * @param ParserOutput &$parserOutput
647 function addParserOutput( &$parserOutput ) {
648 $this->addParserOutputNoText( $parserOutput );
649 $text = $parserOutput->getText();
650 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
651 $this->addHTML( $text );
655 * Add wikitext to the buffer, assuming that this is the primary text for a page view
656 * Saves the text into the parser cache if possible.
658 * @param string $text
659 * @param Article $article
661 * @deprecated Use Article::outputWikitext
663 public function addPrimaryWikiText( $text, $article, $cache = true ) {
666 wfDeprecated( __METHOD__
);
668 $popts = $this->parserOptions();
669 $popts->setTidy(true);
670 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
671 $popts, true, true, $this->mRevisionId
);
672 $popts->setTidy(false);
673 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
674 $parserCache = ParserCache
::singleton();
675 $parserCache->save( $parserOutput, $article, $popts);
678 $this->addParserOutput( $parserOutput );
682 * @deprecated use addWikiTextTidy()
684 public function addSecondaryWikiText( $text, $linestart = true ) {
685 wfDeprecated( __METHOD__
);
686 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
690 * Add wikitext with tidy enabled
692 public function addWikiTextTidy( $text, $linestart = true ) {
693 $title = $this->getTitle();
694 $this->addWikiTextTitleTidy($text, $title, $linestart);
699 * Add the output of a QuickTemplate to the output buffer
701 * @param QuickTemplate $template
703 public function addTemplate( &$template ) {
705 $template->execute();
706 $this->addHTML( ob_get_contents() );
711 * Parse wikitext and return the HTML.
713 * @param string $text
714 * @param bool $linestart Is this the start of a line?
715 * @param bool $interface ??
717 public function parse( $text, $linestart = true, $interface = false ) {
719 if( is_null( $this->getTitle() ) ) {
720 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
722 $popts = $this->parserOptions();
723 if ( $interface) { $popts->setInterfaceMessage(true); }
724 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
725 $linestart, true, $this->mRevisionId
);
726 if ( $interface) { $popts->setInterfaceMessage(false); }
727 return $parserOutput->getText();
730 /** Parse wikitext, strip paragraphs, and return the HTML. */
731 public function parseInline( $text, $linestart = true, $interface = false ) {
732 $parsed = $this->parse( $text, $linestart, $interface );
735 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
743 * @param Article $article
748 * @return bool True if successful, else false.
750 public function tryParserCache( &$article ) {
751 wfDeprecated( __METHOD__
);
752 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
754 if ($parserOutput !== false) {
755 $this->addParserOutput( $parserOutput );
763 * @param int $maxage Maximum cache time on the Squid, in seconds.
765 public function setSquidMaxage( $maxage ) {
766 $this->mSquidMaxage
= $maxage;
770 * Use enableClientCache(false) to force it to send nocache headers
773 public function enableClientCache( $state ) {
774 return wfSetVar( $this->mEnableClientCache
, $state );
777 function getCacheVaryCookies() {
778 global $wgCookiePrefix, $wgCacheVaryCookies;
780 if ( $cookies === null ) {
781 $cookies = array_merge(
783 "{$wgCookiePrefix}Token",
784 "{$wgCookiePrefix}LoggedOut",
789 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
794 function uncacheableBecauseRequestVars() {
796 return $wgRequest->getText('useskin', false) === false
797 && $wgRequest->getText('uselang', false) === false;
801 * Check if the request has a cache-varying cookie header
802 * If it does, it's very important that we don't allow public caching
804 function haveCacheVaryCookies() {
806 $cookieHeader = $wgRequest->getHeader( 'cookie' );
807 if ( $cookieHeader === false ) {
810 $cvCookies = $this->getCacheVaryCookies();
811 foreach ( $cvCookies as $cookieName ) {
812 # Check for a simple string match, like the way squid does it
813 if ( strpos( $cookieHeader, $cookieName ) ) {
814 wfDebug( __METHOD__
.": found $cookieName\n" );
818 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
822 public function addVaryHeader( $header, $option = null ) {
823 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
824 $this->mVaryHeader
[$header] = $option;
826 elseif( is_array( $option ) ) {
827 if( is_array( $this->mVaryHeader
[$header] ) ) {
828 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
831 $this->mVaryHeader
[$header] = $option;
834 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
837 /** Get a complete X-Vary-Options header */
838 public function getXVO() {
839 $cvCookies = $this->getCacheVaryCookies();
841 $cookiesOption = array();
842 foreach ( $cvCookies as $cookieName ) {
843 $cookiesOption[] = 'string-contains=' . $cookieName;
845 $this->addVaryHeader( 'Cookie', $cookiesOption );
848 foreach( $this->mVaryHeader
as $header => $option ) {
849 $newheader = $header;
850 if( is_array( $option ) )
851 $newheader .= ';' . implode( ';', $option );
852 $headers[] = $newheader;
854 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
859 /** bug 21672: Add Accept-Language to Vary and XVO headers
860 if there's no 'variant' parameter existed in GET.
863 /w/index.php?title=Main_page should always be served; but
864 /w/index.php?title=Main_page&variant=zh-cn should never be served.
866 patched by Liangent and Philip */
867 function addAcceptLanguage() {
868 global $wgRequest, $wgContLang;
869 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
870 $variants = $wgContLang->getVariants();
872 foreach ( $variants as $variant ) {
873 if( $variant === $wgContLang->getCode() )
876 $aloption[] = "string-contains=$variant";
878 $this->addVaryHeader( 'Accept-Language', $aloption );
882 public function sendCacheControl() {
883 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
885 $response = $wgRequest->response();
886 if ($wgUseETag && $this->mETag
)
887 $response->header("ETag: $this->mETag");
889 $this->addAcceptLanguage();
891 # don't serve compressed data to clients who can't handle it
892 # maintain different caches for logged-in users and non-logged in ones
893 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
896 # Add an X-Vary-Options header for Squid with Wikimedia patches
897 $response->header( $this->getXVO() );
900 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
901 if( $wgUseSquid && session_id() == '' &&
902 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
905 # We'll purge the proxy cache explicitly, but require end user agents
906 # to revalidate against the proxy on each visit.
907 # Surrogate-Control controls our Squid, Cache-Control downstream caches
908 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
909 # start with a shorter timeout for initial testing
910 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
911 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
912 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
914 # We'll purge the proxy cache for anons explicitly, but require end user agents
915 # to revalidate against the proxy on each visit.
916 # IMPORTANT! The Squid needs to replace the Cache-Control header with
917 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
918 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
919 # start with a shorter timeout for initial testing
920 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
921 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
924 # We do want clients to cache if they can, but they *must* check for updates
925 # on revisiting the page.
926 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
927 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
928 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
930 if($this->mLastModified
) {
931 $response->header( "Last-Modified: {$this->mLastModified}" );
934 wfDebug( __METHOD__
. ": no caching **\n", false );
936 # In general, the absence of a last modified header should be enough to prevent
937 # the client from using its cache. We send a few other things just to make sure.
938 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
939 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
940 $response->header( 'Pragma: no-cache' );
942 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
946 * Get the message associed with the HTTP response code $code
948 * @param $code Integer: status code
949 * @return String or null: message or null if $code is not in the list of
952 public static function getStatusMessage( $code ) {
953 static $statusMessage = array(
955 101 => 'Switching Protocols',
960 203 => 'Non-Authoritative Information',
962 205 => 'Reset Content',
963 206 => 'Partial Content',
964 207 => 'Multi-Status',
965 300 => 'Multiple Choices',
966 301 => 'Moved Permanently',
969 304 => 'Not Modified',
971 307 => 'Temporary Redirect',
972 400 => 'Bad Request',
973 401 => 'Unauthorized',
974 402 => 'Payment Required',
977 405 => 'Method Not Allowed',
978 406 => 'Not Acceptable',
979 407 => 'Proxy Authentication Required',
980 408 => 'Request Timeout',
983 411 => 'Length Required',
984 412 => 'Precondition Failed',
985 413 => 'Request Entity Too Large',
986 414 => 'Request-URI Too Large',
987 415 => 'Unsupported Media Type',
988 416 => 'Request Range Not Satisfiable',
989 417 => 'Expectation Failed',
990 422 => 'Unprocessable Entity',
992 424 => 'Failed Dependency',
993 500 => 'Internal Server Error',
994 501 => 'Not Implemented',
995 502 => 'Bad Gateway',
996 503 => 'Service Unavailable',
997 504 => 'Gateway Timeout',
998 505 => 'HTTP Version Not Supported',
999 507 => 'Insufficient Storage'
1001 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1005 * Finally, all the text has been munged and accumulated into
1006 * the object, let's actually output it:
1008 public function output() {
1009 global $wgUser, $wgOutputEncoding, $wgRequest;
1010 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1011 global $wgUseAjax, $wgAjaxWatch;
1012 global $wgEnableMWSuggest, $wgUniversalEditButton;
1015 if( $this->mDoNothing
){
1018 wfProfileIn( __METHOD__
);
1019 if ( $this->mRedirect
!= '' ) {
1020 # Standards require redirect URLs to be absolute
1021 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1022 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1023 if( !$wgDebugRedirects ) {
1024 $message = self
::getStatusMessage( $this->mRedirectCode
);
1025 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1027 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1029 $this->sendCacheControl();
1031 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1032 if( $wgDebugRedirects ) {
1033 $url = htmlspecialchars( $this->mRedirect
);
1034 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1035 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1036 print "</body>\n</html>\n";
1038 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1040 wfProfileOut( __METHOD__
);
1042 } elseif ( $this->mStatusCode
) {
1043 $message = self
::getStatusMessage( $this->mStatusCode
);
1045 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1048 $sk = $wgUser->getSkin();
1051 $this->addScriptFile( 'ajax.js' );
1053 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1055 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1056 $this->addScriptFile( 'ajaxwatch.js' );
1059 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1060 $this->addScriptFile( 'mwsuggest.js' );
1064 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1065 $this->addScriptFile( 'rightclickedit.js' );
1068 if( $wgUniversalEditButton ) {
1069 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1070 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1071 // Original UniversalEditButton
1072 $msg = wfMsg('edit');
1073 $this->addLink( array(
1074 'rel' => 'alternate',
1075 'type' => 'application/x-wiki',
1077 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1079 // Alternate edit link
1080 $this->addLink( array(
1083 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1088 # Buffer output; final headers may depend on later processing
1091 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1092 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1094 if ($this->mArticleBodyOnly
) {
1095 $this->out($this->mBodytext
);
1097 // Hook that allows last minute changes to the output page, e.g.
1098 // adding of CSS or Javascript by extensions.
1099 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1101 wfProfileIn( 'Output-skin' );
1102 $sk->outputPage( $this );
1103 wfProfileOut( 'Output-skin' );
1106 $this->sendCacheControl();
1108 wfProfileOut( __METHOD__
);
1112 * Actually output something with print(). Performs an iconv to the
1113 * output encoding, if needed.
1114 * @param string $ins The string to output
1116 public function out( $ins ) {
1117 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1118 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1121 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1122 if ( false === $outs ) { $outs = $ins; }
1130 public static function setEncodings() {
1131 global $wgInputEncoding, $wgOutputEncoding;
1134 $wgInputEncoding = strtolower( $wgInputEncoding );
1136 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1137 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1140 $wgOutputEncoding = $wgInputEncoding;
1144 * Deprecated, use wfReportTime() instead.
1148 public function reportTime() {
1149 wfDeprecated( __METHOD__
);
1150 $time = wfReportTime();
1155 * Produce a "user is blocked" page.
1157 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1160 function blockedPage( $return = true ) {
1161 global $wgUser, $wgContLang, $wgLang;
1163 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1164 $this->setRobotPolicy( 'noindex,nofollow' );
1165 $this->setArticleRelated( false );
1167 $name = User
::whoIs( $wgUser->blockedBy() );
1168 $reason = $wgUser->blockedFor();
1169 if( $reason == '' ) {
1170 $reason = wfMsg( 'blockednoreason' );
1172 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1175 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1177 $blockid = $wgUser->mBlock
->mId
;
1179 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1180 if ( $blockExpiry == 'infinity' ) {
1181 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1182 // Search for localization in 'ipboptions'
1183 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1184 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1185 if ( strpos( $option, ":" ) === false )
1187 list( $show, $value ) = explode( ":", $option );
1188 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1189 $blockExpiry = $show;
1194 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1197 if ( $wgUser->mBlock
->mAuto
) {
1198 $msg = 'autoblockedtext';
1200 $msg = 'blockedtext';
1203 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1204 * This could be a username, an ip range, or a single ip. */
1205 $intended = $wgUser->mBlock
->mAddress
;
1207 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1209 # Don't auto-return to special pages
1211 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1212 $this->returnToMain( null, $return );
1217 * Output a standard error page
1219 * @param string $title Message key for page title
1220 * @param string $msg Message key for page text
1221 * @param array $params Message parameters
1223 public function showErrorPage( $title, $msg, $params = array() ) {
1224 if ( $this->getTitle() ) {
1225 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1227 $this->setPageTitle( wfMsg( $title ) );
1228 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1229 $this->setRobotPolicy( 'noindex,nofollow' );
1230 $this->setArticleRelated( false );
1231 $this->enableClientCache( false );
1232 $this->mRedirect
= '';
1233 $this->mBodytext
= '';
1235 array_unshift( $params, 'parse' );
1236 array_unshift( $params, $msg );
1237 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1239 $this->returnToMain();
1243 * Output a standard permission error page
1245 * @param array $errors Error message keys
1247 public function showPermissionsErrorPage( $errors, $action = null )
1249 $this->mDebugtext
.= 'Original title: ' .
1250 $this->getTitle()->getPrefixedText() . "\n";
1251 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1252 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1253 $this->setRobotPolicy( 'noindex,nofollow' );
1254 $this->setArticleRelated( false );
1255 $this->enableClientCache( false );
1256 $this->mRedirect
= '';
1257 $this->mBodytext
= '';
1258 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1262 public function errorpage( $title, $msg ) {
1263 wfDeprecated( __METHOD__
);
1264 throw new ErrorPageError( $title, $msg );
1268 * Display an error page indicating that a given version of MediaWiki is
1269 * required to use it
1271 * @param mixed $version The version of MediaWiki needed to use the page
1273 public function versionRequired( $version ) {
1274 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1275 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1276 $this->setRobotPolicy( 'noindex,nofollow' );
1277 $this->setArticleRelated( false );
1278 $this->mBodytext
= '';
1280 $this->addWikiMsg( 'versionrequiredtext', $version );
1281 $this->returnToMain();
1285 * Display an error page noting that a given permission bit is required.
1287 * @param string $permission key required
1289 public function permissionRequired( $permission ) {
1292 $this->setPageTitle( wfMsg( 'badaccess' ) );
1293 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1294 $this->setRobotPolicy( 'noindex,nofollow' );
1295 $this->setArticleRelated( false );
1296 $this->mBodytext
= '';
1298 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1299 User
::getGroupsWithPermission( $permission ) );
1301 $this->addWikiMsg( 'badaccess-groups',
1302 $wgLang->commaList( $groups ),
1305 $this->addWikiMsg( 'badaccess-group0' );
1307 $this->returnToMain();
1311 * Use permissionRequired.
1314 public function sysopRequired() {
1315 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1319 * Use permissionRequired.
1322 public function developerRequired() {
1323 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1327 * Produce the stock "please login to use the wiki" page
1329 public function loginToUse() {
1330 global $wgUser, $wgContLang;
1332 if( $wgUser->isLoggedIn() ) {
1333 $this->permissionRequired( 'read' );
1337 $skin = $wgUser->getSkin();
1339 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1340 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1341 $this->setRobotPolicy( 'noindex,nofollow' );
1342 $this->setArticleFlag( false );
1344 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1345 $loginLink = $skin->link(
1347 wfMsgHtml( 'loginreqlink' ),
1349 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1350 array( 'known', 'noclasses' )
1352 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1353 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1355 # Don't return to the main page if the user can't read it
1356 # otherwise we'll end up in a pointless loop
1357 $mainPage = Title
::newMainPage();
1358 if( $mainPage->userCanRead() )
1359 $this->returnToMain( null, $mainPage );
1363 public function databaseError( $fname, $sql, $error, $errno ) {
1364 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1368 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1369 * @return string The wikitext error-messages, formatted into a list.
1371 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1372 if ($action == null) {
1373 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1376 $action_desc = wfMsgNoTrans( "action-$action" );
1377 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1380 if (count( $errors ) > 1) {
1381 $text .= '<ul class="permissions-errors">' . "\n";
1383 foreach( $errors as $error )
1386 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1391 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1398 * Display a page stating that the Wiki is in read-only mode,
1399 * and optionally show the source of the page that the user
1400 * was trying to edit. Should only be called (for this
1401 * purpose) after wfReadOnly() has returned true.
1403 * For historical reasons, this function is _also_ used to
1404 * show the error message when a user tries to edit a page
1405 * they are not allowed to edit. (Unless it's because they're
1406 * blocked, then we show blockedPage() instead.) In this
1407 * case, the second parameter should be set to true and a list
1408 * of reasons supplied as the third parameter.
1410 * @todo Needs to be split into multiple functions.
1412 * @param string $source Source code to show (or null).
1413 * @param bool $protected Is this a permissions error?
1414 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1416 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1418 $skin = $wgUser->getSkin();
1420 $this->setRobotPolicy( 'noindex,nofollow' );
1421 $this->setArticleRelated( false );
1423 // If no reason is given, just supply a default "I can't let you do
1424 // that, Dave" message. Should only occur if called by legacy code.
1425 if ( $protected && empty($reasons) ) {
1426 $reasons[] = array( 'badaccess-group0' );
1429 if ( !empty($reasons) ) {
1430 // Permissions error
1432 $this->setPageTitle( wfMsg( 'viewsource' ) );
1441 array( 'known', 'noclasses' )
1446 $this->setPageTitle( wfMsg( 'badaccess' ) );
1448 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1450 // Wiki is read only
1451 $this->setPageTitle( wfMsg( 'readonly' ) );
1452 $reason = wfReadOnlyReason();
1453 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1456 // Show source, if supplied
1457 if( is_string( $source ) ) {
1458 $this->addWikiMsg( 'viewsourcetext' );
1461 'id' => 'wpTextbox1',
1462 'name' => 'wpTextbox1',
1463 'cols' => $wgUser->getOption( 'cols' ),
1464 'rows' => $wgUser->getOption( 'rows' ),
1465 'readonly' => 'readonly'
1467 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1469 // Show templates used by this article
1470 $skin = $wgUser->getSkin();
1471 $article = new Article( $this->getTitle() );
1472 $this->addHTML( "<div class='templatesUsed'>
1473 {$skin->formatTemplates( $article->getUsedTemplates() )}
1478 # If the title doesn't exist, it's fairly pointless to print a return
1479 # link to it. After all, you just tried editing it and couldn't, so
1480 # what's there to do there?
1481 if( $this->getTitle()->exists() ) {
1482 $this->returnToMain( null, $this->getTitle() );
1487 public function fatalError( $message ) {
1488 wfDeprecated( __METHOD__
);
1489 throw new FatalError( $message );
1493 public function unexpectedValueError( $name, $val ) {
1494 wfDeprecated( __METHOD__
);
1495 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1499 public function fileCopyError( $old, $new ) {
1500 wfDeprecated( __METHOD__
);
1501 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1505 public function fileRenameError( $old, $new ) {
1506 wfDeprecated( __METHOD__
);
1507 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1511 public function fileDeleteError( $name ) {
1512 wfDeprecated( __METHOD__
);
1513 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1517 public function fileNotFoundError( $name ) {
1518 wfDeprecated( __METHOD__
);
1519 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1522 public function showFatalError( $message ) {
1523 $this->setPageTitle( wfMsg( "internalerror" ) );
1524 $this->setRobotPolicy( "noindex,nofollow" );
1525 $this->setArticleRelated( false );
1526 $this->enableClientCache( false );
1527 $this->mRedirect
= '';
1528 $this->mBodytext
= $message;
1531 public function showUnexpectedValueError( $name, $val ) {
1532 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1535 public function showFileCopyError( $old, $new ) {
1536 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1539 public function showFileRenameError( $old, $new ) {
1540 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1543 public function showFileDeleteError( $name ) {
1544 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1547 public function showFileNotFoundError( $name ) {
1548 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1552 * Add a "return to" link pointing to a specified title
1554 * @param $title Title to link
1555 * @param $query String: query string
1557 public function addReturnTo( $title, $query = array() ) {
1559 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1560 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1561 $title, null, array(), $query ) );
1562 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1566 * Add a "return to" link pointing to a specified title,
1567 * or the title indicated in the request, or else the main page
1569 * @param $unused No longer used
1570 * @param $returnto Title or String to return to
1571 * @param $returntoquery String: query string for the return to link
1573 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1576 if ( $returnto == null ) {
1577 $returnto = $wgRequest->getText( 'returnto' );
1580 if ( $returntoquery == null ) {
1581 $returntoquery = $wgRequest->getText( 'returntoquery' );
1584 if ( $returnto === '' ) {
1585 $returnto = Title
::newMainPage();
1588 if ( is_object( $returnto ) ) {
1589 $titleObj = $returnto;
1591 $titleObj = Title
::newFromText( $returnto );
1593 if ( !is_object( $titleObj ) ) {
1594 $titleObj = Title
::newMainPage();
1597 $this->addReturnTo( $titleObj, $returntoquery );
1601 * @return string The doctype, opening <html>, and head element.
1603 * @param $sk Skin The given Skin
1605 public function headElement( Skin
$sk, $includeStyle = true ) {
1606 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1607 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1608 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1610 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1611 if ( $sk->commonPrintStylesheet() ) {
1612 $this->addStyle( 'common/wikiprintable.css', 'print' );
1614 $sk->setupUserCss( $this );
1618 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1619 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1622 if ( $this->getHTMLTitle() == '' ) {
1623 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1626 $dir = $wgContLang->getDir();
1629 if ( $wgWellFormedXml ) {
1630 # Unknown elements and attributes are okay in XML, but unknown
1631 # named entities are well-formedness errors and will break XML
1632 # parsers. Thus we need a doctype that gives us appropriate
1633 # entity definitions. The HTML5 spec permits four legacy
1634 # doctypes as obsolete but conforming, so let's pick one of
1635 # those, although it makes our pages look like XHTML1 Strict.
1636 # Isn't compatibility great?
1637 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1640 $ret .= "<!doctype html>\n";
1642 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1643 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1646 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1647 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1648 foreach($wgXhtmlNamespaces as $tag => $ns) {
1649 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1651 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1655 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1656 $ret .= implode( "\n", array(
1657 $this->getHeadLinks(),
1658 $this->buildCssLinks(),
1659 $this->getHeadScripts( $sk ),
1660 $this->getHeadItems(),
1663 $ret .= Html
::inlineStyle( $sk->usercss
);
1666 if ($wgUseTrackbacks && $this->isArticleRelated())
1667 $ret .= $this->getTitle()->trackbackRDF();
1669 $ret .= "</head>\n";
1674 * gets the global variables and mScripts
1676 * also adds userjs to the end if enabled:
1678 function getHeadScripts( Skin
$sk ) {
1679 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1680 global $wgStylePath, $wgStyleVersion;
1682 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1683 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1685 //add site JS if enabled:
1686 if( $wgUseSiteJs ) {
1687 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1688 $this->addScriptFile( Skin
::makeUrl( '-',
1689 "action=raw$jsCache&gen=js&useskin=" .
1690 urlencode( $sk->getSkinName() )
1695 //add user js if enabled:
1696 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1697 $action = $wgRequest->getVal( 'action', 'view' );
1698 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1699 # XXX: additional security check/prompt?
1700 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1702 $userpage = $wgUser->getUserPage();
1703 $userjs = Skin
::makeUrl(
1704 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1705 'action=raw&ctype=' . $wgJsMimeType );
1706 $this->addScriptFile( $userjs );
1710 $scripts .= "\n" . $this->mScripts
;
1714 protected function addDefaultMeta() {
1715 global $wgVersion, $wgHtml5;
1717 static $called = false;
1719 # Don't run this twice
1725 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1727 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1729 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1730 if( $p !== 'index,follow' ) {
1731 // http://www.robotstxt.org/wc/meta-user.html
1732 // Only show if it's different from the default robots policy
1733 $this->addMeta( 'robots', $p );
1736 if ( count( $this->mKeywords
) > 0 ) {
1738 "/<.*?" . ">/" => '',
1741 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1746 * @return string HTML tag links to be put in the header.
1748 public function getHeadLinks() {
1749 global $wgRequest, $wgFeed;
1751 // Ideally this should happen earlier, somewhere. :P
1752 $this->addDefaultMeta();
1756 foreach ( $this->mMetatags
as $tag ) {
1757 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1759 $tag[0] = substr( $tag[0], 5 );
1763 $tags[] = Html
::element( 'meta',
1766 'content' => $tag[1] ) );
1768 foreach ( $this->mLinktags
as $tag ) {
1769 $tags[] = Html
::element( 'link', $tag );
1773 foreach( $this->getSyndicationLinks() as $format => $link ) {
1774 # Use the page name for the title (accessed through $wgTitle since
1775 # there's no other way). In principle, this could lead to issues
1776 # with having the same name for different feeds corresponding to
1777 # the same page, but we can't avoid that at this low a level.
1779 $tags[] = $this->feedLink(
1782 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1785 # Recent changes feed should appear on every page (except recentchanges,
1786 # that would be redundant). Put it after the per-page feed to avoid
1787 # changing existing behavior. It's still available, probably via a
1788 # menu in your browser. Some sites might have a different feed they'd
1789 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1790 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1791 # If so, use it instead.
1793 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1794 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1796 if ( $wgOverrideSiteFeed ) {
1797 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1798 $tags[] = $this->feedLink (
1800 htmlspecialchars( $feedUrl ),
1801 wfMsg( "site-{$type}-feed", $wgSitename ) );
1804 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1805 foreach( $wgFeedClasses as $format => $class ) {
1806 $tags[] = $this->feedLink(
1808 $rctitle->getLocalURL( "feed={$format}" ),
1809 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1814 return implode( "\n", $tags );
1818 * Return URLs for each supported syndication format for this page.
1819 * @return array associating format keys with URLs
1821 public function getSyndicationLinks() {
1822 return $this->mFeedLinks
;
1826 * Generate a <link rel/> for an RSS feed.
1828 private function feedLink( $type, $url, $text ) {
1829 return Html
::element( 'link', array(
1830 'rel' => 'alternate',
1831 'type' => "application/$type+xml",
1837 * Add a local or specified stylesheet, with the given media options.
1838 * Meant primarily for internal use...
1840 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1841 * @param $conditional -- for IE conditional comments, specifying an IE version
1842 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1844 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1846 // Even though we expect the media type to be lowercase, but here we
1847 // force it to lowercase to be safe.
1849 $options['media'] = $media;
1851 $options['condition'] = $condition;
1853 $options['dir'] = $dir;
1854 $this->styles
[$style] = $options;
1858 * Adds inline CSS styles
1859 * @param $style_css Mixed: inline CSS
1861 public function addInlineStyle( $style_css ){
1862 $this->mScripts
.= Html
::inlineStyle( $style_css );
1866 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1867 * These will be applied to various media & IE conditionals.
1869 public function buildCssLinks() {
1871 foreach( $this->styles
as $file => $options ) {
1872 $link = $this->styleLink( $file, $options );
1877 return implode( "\n", $links );
1880 protected function styleLink( $style, $options ) {
1883 if( isset( $options['dir'] ) ) {
1885 $siteDir = $wgContLang->getDir();
1886 if( $siteDir != $options['dir'] )
1890 if( isset( $options['media'] ) ) {
1891 $media = $this->transformCssMedia( $options['media'] );
1892 if( is_null( $media ) ) {
1899 if( substr( $style, 0, 1 ) == '/' ||
1900 substr( $style, 0, 5 ) == 'http:' ||
1901 substr( $style, 0, 6 ) == 'https:' ) {
1904 global $wgStylePath, $wgStyleVersion;
1905 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1908 $link = Html
::linkedStyle( $url, $media );
1910 if( isset( $options['condition'] ) ) {
1911 $condition = htmlspecialchars( $options['condition'] );
1912 $link = "<!--[if $condition]>$link<![endif]-->";
1917 function transformCssMedia( $media ) {
1918 global $wgRequest, $wgHandheldForIPhone;
1920 // Switch in on-screen display for media testing
1922 'printable' => 'print',
1923 'handheld' => 'handheld',
1925 foreach( $switches as $switch => $targetMedia ) {
1926 if( $wgRequest->getBool( $switch ) ) {
1927 if( $media == $targetMedia ) {
1929 } elseif( $media == 'screen' ) {
1935 // Expand longer media queries as iPhone doesn't grok 'handheld'
1936 if( $wgHandheldForIPhone ) {
1937 $mediaAliases = array(
1938 'screen' => 'screen and (min-device-width: 481px)',
1939 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1942 if( isset( $mediaAliases[$media] ) ) {
1943 $media = $mediaAliases[$media];
1951 * Turn off regular page output and return an error reponse
1952 * for when rate limiting has triggered.
1954 public function rateLimited() {
1956 $this->setPageTitle(wfMsg('actionthrottled'));
1957 $this->setRobotPolicy( 'noindex,follow' );
1958 $this->setArticleRelated( false );
1959 $this->enableClientCache( false );
1960 $this->mRedirect
= '';
1962 $this->setStatusCode(503);
1963 $this->addWikiMsg( 'actionthrottledtext' );
1965 $this->returnToMain( null, $this->getTitle() );
1969 * Show an "add new section" link?
1973 public function showNewSectionLink() {
1974 return $this->mNewSectionLink
;
1978 * Forcibly hide the new section link?
1982 public function forceHideNewSectionLink() {
1983 return $this->mHideNewSectionLink
;
1987 * Show a warning about slave lag
1989 * If the lag is higher than $wgSlaveLagCritical seconds,
1990 * then the warning is a bit more obvious. If the lag is
1991 * lower than $wgSlaveLagWarning, then no warning is shown.
1993 * @param int $lag Slave lag
1995 public function showLagWarning( $lag ) {
1996 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
1997 if( $lag >= $wgSlaveLagWarning ) {
1998 $message = $lag < $wgSlaveLagCritical
2001 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2002 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2007 * Add a wikitext-formatted message to the output.
2008 * This is equivalent to:
2010 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2012 public function addWikiMsg( /*...*/ ) {
2013 $args = func_get_args();
2014 $name = array_shift( $args );
2015 $this->addWikiMsgArray( $name, $args );
2019 * Add a wikitext-formatted message to the output.
2020 * Like addWikiMsg() except the parameters are taken as an array
2021 * instead of a variable argument list.
2023 * $options is passed through to wfMsgExt(), see that function for details.
2025 public function addWikiMsgArray( $name, $args, $options = array() ) {
2026 $options[] = 'parse';
2027 $text = wfMsgExt( $name, $options, $args );
2028 $this->addHTML( $text );
2032 * This function takes a number of message/argument specifications, wraps them in
2033 * some overall structure, and then parses the result and adds it to the output.
2035 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2036 * on. The subsequent arguments may either be strings, in which case they are the
2037 * message names, or arrays, in which case the first element is the message name,
2038 * and subsequent elements are the parameters to that message.
2040 * The special named parameter 'options' in a message specification array is passed
2041 * through to the $options parameter of wfMsgExt().
2043 * Don't use this for messages that are not in users interface language.
2047 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2051 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2053 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2054 $msgSpecs = func_get_args();
2055 array_shift( $msgSpecs );
2056 $msgSpecs = array_values( $msgSpecs );
2058 foreach ( $msgSpecs as $n => $spec ) {
2060 if ( is_array( $spec ) ) {
2062 $name = array_shift( $args );
2063 if ( isset( $args['options'] ) ) {
2064 $options = $args['options'];
2065 unset( $args['options'] );
2071 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2073 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );