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 $mDoNothing = false;
25 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
26 var $mIsArticleRelated = true;
27 protected $mParserOptions = null; // lazy initialised, use parserOptions()
29 var $mFeedLinks = array();
31 var $mEnableClientCache = true;
32 var $mArticleBodyOnly = false;
34 var $mNewSectionLink = false;
35 var $mHideNewSectionLink = false;
36 var $mNoGallery = false;
37 var $mPageTitleActionText = '';
38 var $mParseWarnings = array();
39 var $mSquidMaxage = 0;
40 var $mRevisionId = null;
41 protected $mTitle = null;
44 * An array of stylesheet filenames (relative from skins path), with options
45 * for CSS media, IE conditions, and RTL/LTR direction.
46 * For internal use; add settings in the skin via $this->addStyle()
48 var $styles = array();
50 private $mIndexPolicy = 'index';
51 private $mFollowPolicy = 'follow';
52 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
57 * Initialise private variables
59 function __construct() {
60 global $wgAllowUserJs;
61 $this->mAllowUserJs
= $wgAllowUserJs;
64 public function redirect( $url, $responsecode = '302' ) {
65 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
66 $this->mRedirect
= str_replace( "\n", '', $url );
67 $this->mRedirectCode
= $responsecode;
70 public function getRedirect() {
71 return $this->mRedirect
;
75 * Set the HTTP status code to send with the output.
77 * @param int $statusCode
80 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
83 * Add a new <meta> tag
84 * To add an http-equiv meta tag, precede the name with "http:"
86 * @param $name tag name
87 * @param $val tag value
89 function addMeta( $name, $val ) {
90 array_push( $this->mMetatags
, array( $name, $val ) );
93 function addKeyword( $text ) {
94 if( is_array( $text )) {
95 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
97 array_push( $this->mKeywords
, $text );
100 function addScript( $script ) {
101 $this->mScripts
.= $script . "\n";
105 * Register and add a stylesheet from an extension directory.
106 * @param $url String path to sheet. Provide either a full url (beginning
107 * with 'http', etc) or a relative path from the document root
108 * (beginning with '/'). Otherwise it behaves identically to
109 * addStyle() and draws from the /skins folder.
111 public function addExtensionStyle( $url ) {
112 array_push( $this->mExtStyles
, $url );
116 * Add a JavaScript file out of skins/common, or a given relative path.
117 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
119 function addScriptFile( $file ) {
120 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
121 if( substr( $file, 0, 1 ) == '/' ) {
124 $path = "{$wgStylePath}/common/{$file}";
127 Xml
::element( 'script',
129 'type' => $wgJsMimeType,
130 'src' => "$path?$wgStyleVersion",
138 * Add a self-contained script tag with the given contents
139 * @param string $script JavaScript text, no <script> tags
141 function addInlineScript( $script ) {
142 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
146 * Get all registered JS and CSS tags for the header.
148 function getScript() {
149 return $this->mScripts
. $this->getHeadItems();
152 function getHeadItems() {
154 foreach ( $this->mHeadItems
as $item ) {
160 function addHeadItem( $name, $value ) {
161 $this->mHeadItems
[$name] = $value;
164 function hasHeadItem( $name ) {
165 return isset( $this->mHeadItems
[$name] );
168 function setETag($tag) { $this->mETag
= $tag; }
169 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
170 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
172 function addLink( $linkarr ) {
173 # $linkarr should be an associative array of attributes. We'll escape on output.
174 array_push( $this->mLinktags
, $linkarr );
177 # Get all links added by extensions
178 function getExtStyle() {
179 return $this->mExtStyles
;
182 function addMetadataLink( $linkarr ) {
183 # note: buggy CC software only reads first "meta" link
184 static $haveMeta = false;
185 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
186 $this->addLink( $linkarr );
191 * checkLastModified tells the client to use the client-cached page if
192 * possible. If sucessful, the OutputPage is disabled so that
193 * any future call to OutputPage->output() have no effect.
195 * Side effect: sets mLastModified for Last-Modified header
197 * @return bool True iff cache-ok headers was sent.
199 function checkLastModified( $timestamp ) {
200 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
202 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
203 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
206 if( !$wgCachePages ) {
207 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
210 if( $wgUser->getOption( 'nocache' ) ) {
211 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
215 $timestamp = wfTimestamp( TS_MW
, $timestamp );
216 $modifiedTimes = array(
217 'page' => $timestamp,
218 'user' => $wgUser->getTouched(),
219 'epoch' => $wgCacheEpoch
221 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
223 $maxModified = max( $modifiedTimes );
224 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
226 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
227 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
233 foreach ( $modifiedTimes as $name => $value ) {
234 if ( $info !== '' ) {
237 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
240 # IE sends sizes after the date like this:
241 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
242 # this breaks strtotime().
243 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
245 wfSuppressWarnings(); // E_STRICT system time bitching
246 $clientHeaderTime = strtotime( $clientHeader );
248 if ( !$clientHeaderTime ) {
249 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
252 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
254 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
255 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
256 wfDebug( __METHOD__
. ": effective Last-Modified: " .
257 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
258 if( $clientHeaderTime < $maxModified ) {
259 wfDebug( __METHOD__
. ": STALE, $info\n", false );
264 # Give a 304 response code and disable body output
265 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
266 ini_set('zlib.output_compression', 0);
267 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
268 $this->sendCacheControl();
271 // Don't output a compressed blob when using ob_gzhandler;
272 // it's technically against HTTP spec and seems to confuse
273 // Firefox when the response gets split over two packets.
274 wfClearOutputBuffers();
279 function setPageTitleActionText( $text ) {
280 $this->mPageTitleActionText
= $text;
283 function getPageTitleActionText () {
284 if ( isset( $this->mPageTitleActionText
) ) {
285 return $this->mPageTitleActionText
;
290 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
292 * @param $policy string The literal string to output as the contents of
293 * the meta tag. Will be parsed according to the spec and output in
297 public function setRobotPolicy( $policy ) {
298 $policy = Article
::formatRobotPolicy( $policy );
300 if( isset( $policy['index'] ) ){
301 $this->setIndexPolicy( $policy['index'] );
303 if( isset( $policy['follow'] ) ){
304 $this->setFollowPolicy( $policy['follow'] );
309 * Set the index policy for the page, but leave the follow policy un-
312 * @param $policy string Either 'index' or 'noindex'.
315 public function setIndexPolicy( $policy ) {
316 $policy = trim( $policy );
317 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
318 $this->mIndexPolicy
= $policy;
323 * Set the follow policy for the page, but leave the index policy un-
326 * @param $policy string Either 'follow' or 'nofollow'.
329 public function setFollowPolicy( $policy ) {
330 $policy = trim( $policy );
331 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
332 $this->mFollowPolicy
= $policy;
337 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
339 public function setHTMLTitle( $name ) {
340 $this->mHTMLtitle
= $name;
344 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
345 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
346 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
347 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
349 public function setPageTitle( $name ) {
352 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
353 # but leave "<i>foobar</i>" alone
354 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
355 $this->mPagetitle
= $nameWithTags;
357 $taction = $this->getPageTitleActionText();
358 if( !empty( $taction ) ) {
359 $name .= ' - '.$taction;
362 # change "<i>foo&bar</i>" to "foo&bar"
363 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
366 public function setTitle( $t ) {
370 public function getTitle() {
371 if ( $this->mTitle
instanceof Title
) {
372 return $this->mTitle
;
375 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
381 public function getHTMLTitle() { return $this->mHTMLtitle
; }
382 public function getPageTitle() { return $this->mPagetitle
; }
383 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
384 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
385 public function getSubtitle() { return $this->mSubtitle
; }
386 public function isArticle() { return $this->mIsarticle
; }
387 public function setPrintable() { $this->mPrintable
= true; }
388 public function isPrintable() { return $this->mPrintable
; }
389 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
390 public function disable() { $this->mDoNothing
= true; }
391 public function isDisabled() { return $this->mDoNothing
; }
393 public function setSyndicated( $show = true ) {
395 $this->setFeedAppendQuery( false );
397 $this->mFeedLinks
= array();
401 public function setFeedAppendQuery( $val ) {
402 global $wgFeedClasses, $wgAdvertisedFeedTypes;
404 $this->mFeedLinks
= array();
406 foreach ( $wgAdvertisedFeedTypes as $type ) {
407 $query = "feed=$type";
408 if ( is_string( $val ) ) {
409 $query .= '&' . $val;
411 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
415 public function addFeedLink( $format, $href ) {
416 $this->mFeedLinks
[$format] = $href;
419 public function isSyndicated() { return count($this->mFeedLinks
); }
421 public function setArticleRelated( $v ) {
422 $this->mIsArticleRelated
= $v;
424 $this->mIsarticle
= false;
427 public function setArticleFlag( $v ) {
428 $this->mIsarticle
= $v;
430 $this->mIsArticleRelated
= $v;
434 public function isArticleRelated() { return $this->mIsArticleRelated
; }
436 public function getLanguageLinks() { return $this->mLanguageLinks
; }
437 public function addLanguageLinks($newLinkArray) {
438 $this->mLanguageLinks +
= $newLinkArray;
440 public function setLanguageLinks($newLinkArray) {
441 $this->mLanguageLinks
= $newLinkArray;
444 public function getCategoryLinks() {
445 return $this->mCategoryLinks
;
448 public function getCategories() {
449 return $this->mCategories
;
453 * Add an array of categories, with names in the keys
455 public function addCategoryLinks( $categories ) {
456 global $wgUser, $wgContLang;
458 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
462 # Add the links to a LinkBatch
463 $arr = array( NS_CATEGORY
=> $categories );
465 $lb->setArray( $arr );
467 # Fetch existence plus the hiddencat property
468 $dbr = wfGetDB( DB_SLAVE
);
469 $pageTable = $dbr->tableName( 'page' );
470 $where = $lb->constructSet( 'page', $dbr );
471 $propsTable = $dbr->tableName( 'page_props' );
472 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
473 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
474 $res = $dbr->query( $sql, __METHOD__
);
476 # Add the results to the link cache
477 $lb->addResultToCache( LinkCache
::singleton(), $res );
479 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
480 $categories = array_combine( array_keys( $categories ),
481 array_fill( 0, count( $categories ), 'normal' ) );
483 # Mark hidden categories
484 foreach ( $res as $row ) {
485 if ( isset( $row->pp_value
) ) {
486 $categories[$row->page_title
] = 'hidden';
490 # Add the remaining categories to the skin
491 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
492 $sk = $wgUser->getSkin();
493 foreach ( $categories as $category => $type ) {
494 $origcategory = $category;
495 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
496 $wgContLang->findVariantLink( $category, $title, true );
497 if ( $category != $origcategory )
498 if ( array_key_exists( $category, $categories ) )
500 $text = $wgContLang->convertHtml( $title->getText() );
501 $this->mCategories
[] = $title->getText();
502 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
507 public function setCategoryLinks($categories) {
508 $this->mCategoryLinks
= array();
509 $this->addCategoryLinks($categories);
512 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
513 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
515 public function disallowUserJs() { $this->mAllowUserJs
= false; }
516 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
518 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
519 public function addHTML( $text ) { $this->mBodytext
.= $text; }
520 public function clearHTML() { $this->mBodytext
= ''; }
521 public function getHTML() { return $this->mBodytext
; }
522 public function debug( $text ) { $this->mDebugtext
.= $text; }
525 public function setParserOptions( $options ) {
526 wfDeprecated( __METHOD__
);
527 return $this->parserOptions( $options );
530 public function parserOptions( $options = null ) {
531 if ( !$this->mParserOptions
) {
532 $this->mParserOptions
= new ParserOptions
;
534 return wfSetVar( $this->mParserOptions
, $options );
538 * Set the revision ID which will be seen by the wiki text parser
539 * for things such as embedded {{REVISIONID}} variable use.
540 * @param mixed $revid an integer, or NULL
541 * @return mixed previous value
543 public function setRevisionId( $revid ) {
544 $val = is_null( $revid ) ?
null : intval( $revid );
545 return wfSetVar( $this->mRevisionId
, $val );
548 public function getRevisionId() {
549 return $this->mRevisionId
;
553 * Convert wikitext to HTML and add it to the buffer
554 * Default assumes that the current page title will
557 * @param string $text
558 * @param bool $linestart
560 public function addWikiText( $text, $linestart = true ) {
561 $title = $this->getTitle(); // Work arround E_STRICT
562 $this->addWikiTextTitle( $text, $title, $linestart );
565 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
566 $this->addWikiTextTitle($text, $title, $linestart);
569 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
570 $this->addWikiTextTitle( $text, $title, $linestart, true );
573 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
576 wfProfileIn( __METHOD__
);
578 wfIncrStats( 'pcache_not_possible' );
580 $popts = $this->parserOptions();
581 $oldTidy = $popts->setTidy( $tidy );
583 $parserOutput = $wgParser->parse( $text, $title, $popts,
584 $linestart, true, $this->mRevisionId
);
586 $popts->setTidy( $oldTidy );
588 $this->addParserOutput( $parserOutput );
590 wfProfileOut( __METHOD__
);
595 * @param ParserOutput object &$parserOutput
597 public function addParserOutputNoText( &$parserOutput ) {
598 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
600 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
601 $this->addCategoryLinks( $parserOutput->getCategories() );
602 $this->mNewSectionLink
= $parserOutput->getNewSection();
603 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
605 $this->mParseWarnings
= $parserOutput->getWarnings();
606 if ( $parserOutput->getCacheTime() == -1 ) {
607 $this->enableClientCache( false );
609 $this->mNoGallery
= $parserOutput->getNoGallery();
610 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
612 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
613 if ( isset( $this->mTemplateIds
[$ns] ) ) {
614 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
616 $this->mTemplateIds
[$ns] = $dbks;
620 $dt = $parserOutput->getDisplayTitle();
621 $title = $parserOutput->getTitleText();
622 if ( $dt !== false ) {
623 $this->setPageTitle( $dt );
625 else if ( $title != '' ) {
626 $this->setPageTitle( $title );
629 // Hooks registered in the object
630 global $wgParserOutputHooks;
631 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
632 list( $hookName, $data ) = $hookInfo;
633 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
634 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
638 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
643 * @param ParserOutput &$parserOutput
645 function addParserOutput( &$parserOutput ) {
646 $this->addParserOutputNoText( $parserOutput );
647 $text = $parserOutput->getText();
648 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
649 $this->addHTML( $text );
653 * Add wikitext to the buffer, assuming that this is the primary text for a page view
654 * Saves the text into the parser cache if possible.
656 * @param string $text
657 * @param Article $article
659 * @deprecated Use Article::outputWikitext
661 public function addPrimaryWikiText( $text, $article, $cache = true ) {
664 wfDeprecated( __METHOD__
);
666 $popts = $this->parserOptions();
667 $popts->setTidy(true);
668 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
669 $popts, true, true, $this->mRevisionId
);
670 $popts->setTidy(false);
671 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
672 $parserCache = ParserCache
::singleton();
673 $parserCache->save( $parserOutput, $article, $popts);
676 $this->addParserOutput( $parserOutput );
680 * @deprecated use addWikiTextTidy()
682 public function addSecondaryWikiText( $text, $linestart = true ) {
683 wfDeprecated( __METHOD__
);
684 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
688 * Add wikitext with tidy enabled
690 public function addWikiTextTidy( $text, $linestart = true ) {
691 $title = $this->getTitle();
692 $this->addWikiTextTitleTidy($text, $title, $linestart);
697 * Add the output of a QuickTemplate to the output buffer
699 * @param QuickTemplate $template
701 public function addTemplate( &$template ) {
703 $template->execute();
704 $this->addHTML( ob_get_contents() );
709 * Parse wikitext and return the HTML.
711 * @param string $text
712 * @param bool $linestart Is this the start of a line?
713 * @param bool $interface ??
715 public function parse( $text, $linestart = true, $interface = false ) {
717 if( is_null( $this->getTitle() ) ) {
718 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
720 $popts = $this->parserOptions();
721 if ( $interface) { $popts->setInterfaceMessage(true); }
722 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
723 $linestart, true, $this->mRevisionId
);
724 if ( $interface) { $popts->setInterfaceMessage(false); }
725 return $parserOutput->getText();
728 /** Parse wikitext, strip paragraphs, and return the HTML. */
729 public function parseInline( $text, $linestart = true, $interface = false ) {
730 $parsed = $this->parse( $text, $linestart, $interface );
733 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
741 * @param Article $article
746 * @return bool True if successful, else false.
748 public function tryParserCache( &$article ) {
749 wfDeprecated( __METHOD__
);
750 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
752 if ($parserOutput !== false) {
753 $this->addParserOutput( $parserOutput );
761 * @param int $maxage Maximum cache time on the Squid, in seconds.
763 public function setSquidMaxage( $maxage ) {
764 $this->mSquidMaxage
= $maxage;
768 * Use enableClientCache(false) to force it to send nocache headers
771 public function enableClientCache( $state ) {
772 return wfSetVar( $this->mEnableClientCache
, $state );
775 function getCacheVaryCookies() {
776 global $wgCookiePrefix, $wgCacheVaryCookies;
778 if ( $cookies === null ) {
779 $cookies = array_merge(
781 "{$wgCookiePrefix}Token",
782 "{$wgCookiePrefix}LoggedOut",
787 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
792 function uncacheableBecauseRequestVars() {
794 return $wgRequest->getText('useskin', false) === false
795 && $wgRequest->getText('uselang', false) === false;
799 * Check if the request has a cache-varying cookie header
800 * If it does, it's very important that we don't allow public caching
802 function haveCacheVaryCookies() {
804 $cookieHeader = $wgRequest->getHeader( 'cookie' );
805 if ( $cookieHeader === false ) {
808 $cvCookies = $this->getCacheVaryCookies();
809 foreach ( $cvCookies as $cookieName ) {
810 # Check for a simple string match, like the way squid does it
811 if ( strpos( $cookieHeader, $cookieName ) ) {
812 wfDebug( __METHOD__
.": found $cookieName\n" );
816 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
820 public function addVaryHeader( $header, $option = null ) {
821 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
822 $this->mVaryHeader
[$header] = $option;
824 elseif( is_array( $option ) ) {
825 if( is_array( $this->mVaryHeader
[$header] ) ) {
826 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
829 $this->mVaryHeader
[$header] = $option;
832 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
835 /** Get a complete X-Vary-Options header */
836 public function getXVO() {
837 $cvCookies = $this->getCacheVaryCookies();
839 $cookiesOption = array();
840 foreach ( $cvCookies as $cookieName ) {
841 $cookiesOption[] = 'string-contains=' . $cookieName;
843 $this->addVaryHeader( 'Cookie', $cookiesOption );
846 foreach( $this->mVaryHeader
as $header => $option ) {
847 $newheader = $header;
848 if( is_array( $option ) )
849 $newheader .= ';' . implode( ';', $option );
850 $headers[] = $newheader;
852 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
857 /** bug 21672: Add Accept-Language to Vary and XVO headers
858 if there's no 'variant' parameter existed in GET.
861 /w/index.php?title=Main_page should always be served; but
862 /w/index.php?title=Main_page&variant=zh-cn should never be served.
864 patched by Liangent and Philip */
865 function addAcceptLanguage() {
866 global $wgRequest, $wgContLang;
867 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
868 $variants = $wgContLang->getVariants();
870 foreach ( $variants as $variant ) {
871 if( $variant === $wgContLang->getCode() )
874 $aloption[] = "string-contains=$variant";
876 $this->addVaryHeader( 'Accept-Language', $aloption );
880 public function sendCacheControl() {
881 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
883 $response = $wgRequest->response();
884 if ($wgUseETag && $this->mETag
)
885 $response->header("ETag: $this->mETag");
887 $this->addAcceptLanguage();
889 # don't serve compressed data to clients who can't handle it
890 # maintain different caches for logged-in users and non-logged in ones
891 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
894 # Add an X-Vary-Options header for Squid with Wikimedia patches
895 $response->header( $this->getXVO() );
898 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
899 if( $wgUseSquid && session_id() == '' &&
900 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
903 # We'll purge the proxy cache explicitly, but require end user agents
904 # to revalidate against the proxy on each visit.
905 # Surrogate-Control controls our Squid, Cache-Control downstream caches
906 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
907 # start with a shorter timeout for initial testing
908 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
909 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
910 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
912 # We'll purge the proxy cache for anons explicitly, but require end user agents
913 # to revalidate against the proxy on each visit.
914 # IMPORTANT! The Squid needs to replace the Cache-Control header with
915 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
916 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
917 # start with a shorter timeout for initial testing
918 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
919 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
922 # We do want clients to cache if they can, but they *must* check for updates
923 # on revisiting the page.
924 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
925 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
926 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
928 if($this->mLastModified
) {
929 $response->header( "Last-Modified: {$this->mLastModified}" );
932 wfDebug( __METHOD__
. ": no caching **\n", false );
934 # In general, the absence of a last modified header should be enough to prevent
935 # the client from using its cache. We send a few other things just to make sure.
936 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
937 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
938 $response->header( 'Pragma: no-cache' );
940 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
944 * Get the message associed with the HTTP response code $code
946 * @param $code Integer: status code
947 * @return String or null: message or null if $code is not in the list of
950 public static function getStatusMessage( $code ) {
951 static $statusMessage = array(
953 101 => 'Switching Protocols',
958 203 => 'Non-Authoritative Information',
960 205 => 'Reset Content',
961 206 => 'Partial Content',
962 207 => 'Multi-Status',
963 300 => 'Multiple Choices',
964 301 => 'Moved Permanently',
967 304 => 'Not Modified',
969 307 => 'Temporary Redirect',
970 400 => 'Bad Request',
971 401 => 'Unauthorized',
972 402 => 'Payment Required',
975 405 => 'Method Not Allowed',
976 406 => 'Not Acceptable',
977 407 => 'Proxy Authentication Required',
978 408 => 'Request Timeout',
981 411 => 'Length Required',
982 412 => 'Precondition Failed',
983 413 => 'Request Entity Too Large',
984 414 => 'Request-URI Too Large',
985 415 => 'Unsupported Media Type',
986 416 => 'Request Range Not Satisfiable',
987 417 => 'Expectation Failed',
988 422 => 'Unprocessable Entity',
990 424 => 'Failed Dependency',
991 500 => 'Internal Server Error',
992 501 => 'Not Implemented',
993 502 => 'Bad Gateway',
994 503 => 'Service Unavailable',
995 504 => 'Gateway Timeout',
996 505 => 'HTTP Version Not Supported',
997 507 => 'Insufficient Storage'
999 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1003 * Finally, all the text has been munged and accumulated into
1004 * the object, let's actually output it:
1006 public function output() {
1007 global $wgUser, $wgOutputEncoding, $wgRequest;
1008 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1009 global $wgUseAjax, $wgAjaxWatch;
1010 global $wgEnableMWSuggest, $wgUniversalEditButton;
1013 if( $this->mDoNothing
){
1016 wfProfileIn( __METHOD__
);
1017 if ( $this->mRedirect
!= '' ) {
1018 # Standards require redirect URLs to be absolute
1019 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1020 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1021 if( !$wgDebugRedirects ) {
1022 $message = self
::getStatusMessage( $this->mRedirectCode
);
1023 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1025 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1027 $this->sendCacheControl();
1029 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1030 if( $wgDebugRedirects ) {
1031 $url = htmlspecialchars( $this->mRedirect
);
1032 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1033 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1034 print "</body>\n</html>\n";
1036 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1038 wfProfileOut( __METHOD__
);
1040 } elseif ( $this->mStatusCode
) {
1041 $message = self
::getStatusMessage( $this->mStatusCode
);
1043 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1046 $sk = $wgUser->getSkin();
1049 $this->addScriptFile( 'ajax.js' );
1051 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1053 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1054 $this->addScriptFile( 'ajaxwatch.js' );
1057 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1058 $this->addScriptFile( 'mwsuggest.js' );
1062 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1063 $this->addScriptFile( 'rightclickedit.js' );
1066 if( $wgUniversalEditButton ) {
1067 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1068 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1069 // Original UniversalEditButton
1070 $msg = wfMsg('edit');
1071 $this->addLink( array(
1072 'rel' => 'alternate',
1073 'type' => 'application/x-wiki',
1075 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1077 // Alternate edit link
1078 $this->addLink( array(
1081 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1086 # Buffer output; final headers may depend on later processing
1089 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1090 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1092 if ($this->mArticleBodyOnly
) {
1093 $this->out($this->mBodytext
);
1095 // Hook that allows last minute changes to the output page, e.g.
1096 // adding of CSS or Javascript by extensions.
1097 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1099 wfProfileIn( 'Output-skin' );
1100 $sk->outputPage( $this );
1101 wfProfileOut( 'Output-skin' );
1104 $this->sendCacheControl();
1106 wfProfileOut( __METHOD__
);
1110 * Actually output something with print(). Performs an iconv to the
1111 * output encoding, if needed.
1112 * @param string $ins The string to output
1114 public function out( $ins ) {
1115 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1116 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1119 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1120 if ( false === $outs ) { $outs = $ins; }
1128 public static function setEncodings() {
1129 global $wgInputEncoding, $wgOutputEncoding;
1132 $wgInputEncoding = strtolower( $wgInputEncoding );
1134 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1135 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1138 $wgOutputEncoding = $wgInputEncoding;
1142 * Deprecated, use wfReportTime() instead.
1146 public function reportTime() {
1147 wfDeprecated( __METHOD__
);
1148 $time = wfReportTime();
1153 * Produce a "user is blocked" page.
1155 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1158 function blockedPage( $return = true ) {
1159 global $wgUser, $wgContLang, $wgLang;
1161 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1162 $this->setRobotPolicy( 'noindex,nofollow' );
1163 $this->setArticleRelated( false );
1165 $name = User
::whoIs( $wgUser->blockedBy() );
1166 $reason = $wgUser->blockedFor();
1167 if( $reason == '' ) {
1168 $reason = wfMsg( 'blockednoreason' );
1170 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1173 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1175 $blockid = $wgUser->mBlock
->mId
;
1177 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1178 if ( $blockExpiry == 'infinity' ) {
1179 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1180 // Search for localization in 'ipboptions'
1181 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1182 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1183 if ( strpos( $option, ":" ) === false )
1185 list( $show, $value ) = explode( ":", $option );
1186 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1187 $blockExpiry = $show;
1192 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1195 if ( $wgUser->mBlock
->mAuto
) {
1196 $msg = 'autoblockedtext';
1198 $msg = 'blockedtext';
1201 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1202 * This could be a username, an ip range, or a single ip. */
1203 $intended = $wgUser->mBlock
->mAddress
;
1205 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1207 # Don't auto-return to special pages
1209 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1210 $this->returnToMain( null, $return );
1215 * Output a standard error page
1217 * @param string $title Message key for page title
1218 * @param string $msg Message key for page text
1219 * @param array $params Message parameters
1221 public function showErrorPage( $title, $msg, $params = array() ) {
1222 if ( $this->getTitle() ) {
1223 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1225 $this->setPageTitle( wfMsg( $title ) );
1226 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1227 $this->setRobotPolicy( 'noindex,nofollow' );
1228 $this->setArticleRelated( false );
1229 $this->enableClientCache( false );
1230 $this->mRedirect
= '';
1231 $this->mBodytext
= '';
1233 array_unshift( $params, 'parse' );
1234 array_unshift( $params, $msg );
1235 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1237 $this->returnToMain();
1241 * Output a standard permission error page
1243 * @param array $errors Error message keys
1245 public function showPermissionsErrorPage( $errors, $action = null )
1247 $this->mDebugtext
.= 'Original title: ' .
1248 $this->getTitle()->getPrefixedText() . "\n";
1249 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1250 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1251 $this->setRobotPolicy( 'noindex,nofollow' );
1252 $this->setArticleRelated( false );
1253 $this->enableClientCache( false );
1254 $this->mRedirect
= '';
1255 $this->mBodytext
= '';
1256 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1260 public function errorpage( $title, $msg ) {
1261 wfDeprecated( __METHOD__
);
1262 throw new ErrorPageError( $title, $msg );
1266 * Display an error page indicating that a given version of MediaWiki is
1267 * required to use it
1269 * @param mixed $version The version of MediaWiki needed to use the page
1271 public function versionRequired( $version ) {
1272 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1273 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1274 $this->setRobotPolicy( 'noindex,nofollow' );
1275 $this->setArticleRelated( false );
1276 $this->mBodytext
= '';
1278 $this->addWikiMsg( 'versionrequiredtext', $version );
1279 $this->returnToMain();
1283 * Display an error page noting that a given permission bit is required.
1285 * @param string $permission key required
1287 public function permissionRequired( $permission ) {
1290 $this->setPageTitle( wfMsg( 'badaccess' ) );
1291 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1292 $this->setRobotPolicy( 'noindex,nofollow' );
1293 $this->setArticleRelated( false );
1294 $this->mBodytext
= '';
1296 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1297 User
::getGroupsWithPermission( $permission ) );
1299 $this->addWikiMsg( 'badaccess-groups',
1300 $wgLang->commaList( $groups ),
1303 $this->addWikiMsg( 'badaccess-group0' );
1305 $this->returnToMain();
1309 * Use permissionRequired.
1312 public function sysopRequired() {
1313 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1317 * Use permissionRequired.
1320 public function developerRequired() {
1321 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1325 * Produce the stock "please login to use the wiki" page
1327 public function loginToUse() {
1328 global $wgUser, $wgContLang;
1330 if( $wgUser->isLoggedIn() ) {
1331 $this->permissionRequired( 'read' );
1335 $skin = $wgUser->getSkin();
1337 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1338 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1339 $this->setRobotPolicy( 'noindex,nofollow' );
1340 $this->setArticleFlag( false );
1342 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1343 $loginLink = $skin->link(
1345 wfMsgHtml( 'loginreqlink' ),
1347 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1348 array( 'known', 'noclasses' )
1350 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1351 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1353 # Don't return to the main page if the user can't read it
1354 # otherwise we'll end up in a pointless loop
1355 $mainPage = Title
::newMainPage();
1356 if( $mainPage->userCanRead() )
1357 $this->returnToMain( null, $mainPage );
1361 public function databaseError( $fname, $sql, $error, $errno ) {
1362 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1366 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1367 * @return string The wikitext error-messages, formatted into a list.
1369 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1370 if ($action == null) {
1371 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1374 $action_desc = wfMsgNoTrans( "action-$action" );
1375 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1378 if (count( $errors ) > 1) {
1379 $text .= '<ul class="permissions-errors">' . "\n";
1381 foreach( $errors as $error )
1384 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1389 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1396 * Display a page stating that the Wiki is in read-only mode,
1397 * and optionally show the source of the page that the user
1398 * was trying to edit. Should only be called (for this
1399 * purpose) after wfReadOnly() has returned true.
1401 * For historical reasons, this function is _also_ used to
1402 * show the error message when a user tries to edit a page
1403 * they are not allowed to edit. (Unless it's because they're
1404 * blocked, then we show blockedPage() instead.) In this
1405 * case, the second parameter should be set to true and a list
1406 * of reasons supplied as the third parameter.
1408 * @todo Needs to be split into multiple functions.
1410 * @param string $source Source code to show (or null).
1411 * @param bool $protected Is this a permissions error?
1412 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1414 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1416 $skin = $wgUser->getSkin();
1418 $this->setRobotPolicy( 'noindex,nofollow' );
1419 $this->setArticleRelated( false );
1421 // If no reason is given, just supply a default "I can't let you do
1422 // that, Dave" message. Should only occur if called by legacy code.
1423 if ( $protected && empty($reasons) ) {
1424 $reasons[] = array( 'badaccess-group0' );
1427 if ( !empty($reasons) ) {
1428 // Permissions error
1430 $this->setPageTitle( wfMsg( 'viewsource' ) );
1439 array( 'known', 'noclasses' )
1444 $this->setPageTitle( wfMsg( 'badaccess' ) );
1446 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1448 // Wiki is read only
1449 $this->setPageTitle( wfMsg( 'readonly' ) );
1450 $reason = wfReadOnlyReason();
1451 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1454 // Show source, if supplied
1455 if( is_string( $source ) ) {
1456 $this->addWikiMsg( 'viewsourcetext' );
1459 'id' => 'wpTextbox1',
1460 'name' => 'wpTextbox1',
1461 'cols' => $wgUser->getOption( 'cols' ),
1462 'rows' => $wgUser->getOption( 'rows' ),
1463 'readonly' => 'readonly'
1465 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1467 // Show templates used by this article
1468 $skin = $wgUser->getSkin();
1469 $article = new Article( $this->getTitle() );
1470 $this->addHTML( "<div class='templatesUsed'>
1471 {$skin->formatTemplates( $article->getUsedTemplates() )}
1476 # If the title doesn't exist, it's fairly pointless to print a return
1477 # link to it. After all, you just tried editing it and couldn't, so
1478 # what's there to do there?
1479 if( $this->getTitle()->exists() ) {
1480 $this->returnToMain( null, $this->getTitle() );
1485 public function fatalError( $message ) {
1486 wfDeprecated( __METHOD__
);
1487 throw new FatalError( $message );
1491 public function unexpectedValueError( $name, $val ) {
1492 wfDeprecated( __METHOD__
);
1493 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1497 public function fileCopyError( $old, $new ) {
1498 wfDeprecated( __METHOD__
);
1499 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1503 public function fileRenameError( $old, $new ) {
1504 wfDeprecated( __METHOD__
);
1505 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1509 public function fileDeleteError( $name ) {
1510 wfDeprecated( __METHOD__
);
1511 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1515 public function fileNotFoundError( $name ) {
1516 wfDeprecated( __METHOD__
);
1517 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1520 public function showFatalError( $message ) {
1521 $this->setPageTitle( wfMsg( "internalerror" ) );
1522 $this->setRobotPolicy( "noindex,nofollow" );
1523 $this->setArticleRelated( false );
1524 $this->enableClientCache( false );
1525 $this->mRedirect
= '';
1526 $this->mBodytext
= $message;
1529 public function showUnexpectedValueError( $name, $val ) {
1530 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1533 public function showFileCopyError( $old, $new ) {
1534 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1537 public function showFileRenameError( $old, $new ) {
1538 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1541 public function showFileDeleteError( $name ) {
1542 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1545 public function showFileNotFoundError( $name ) {
1546 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1550 * Add a "return to" link pointing to a specified title
1552 * @param $title Title to link
1553 * @param $query String: query string
1555 public function addReturnTo( $title, $query = array() ) {
1557 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1558 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1559 $title, null, array(), $query ) );
1560 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1564 * Add a "return to" link pointing to a specified title,
1565 * or the title indicated in the request, or else the main page
1567 * @param $unused No longer used
1568 * @param $returnto Title or String to return to
1569 * @param $returntoquery String: query string for the return to link
1571 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1574 if ( $returnto == null ) {
1575 $returnto = $wgRequest->getText( 'returnto' );
1578 if ( $returntoquery == null ) {
1579 $returntoquery = $wgRequest->getText( 'returntoquery' );
1582 if ( $returnto === '' ) {
1583 $returnto = Title
::newMainPage();
1586 if ( is_object( $returnto ) ) {
1587 $titleObj = $returnto;
1589 $titleObj = Title
::newFromText( $returnto );
1591 if ( !is_object( $titleObj ) ) {
1592 $titleObj = Title
::newMainPage();
1595 $this->addReturnTo( $titleObj, $returntoquery );
1599 * @return string The doctype, opening <html>, and head element.
1601 * @param $sk Skin The given Skin
1603 public function headElement( Skin
$sk, $includeStyle = true ) {
1604 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1605 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1606 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1608 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1609 if ( $sk->commonPrintStylesheet() ) {
1610 $this->addStyle( 'common/wikiprintable.css', 'print' );
1612 $sk->setupUserCss( $this );
1616 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1617 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1620 if ( $this->getHTMLTitle() == '' ) {
1621 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1624 $dir = $wgContLang->getDir();
1627 if ( $wgWellFormedXml ) {
1628 # Unknown elements and attributes are okay in XML, but unknown
1629 # named entities are well-formedness errors and will break XML
1630 # parsers. Thus we need a doctype that gives us appropriate
1631 # entity definitions. The HTML5 spec permits four legacy
1632 # doctypes as obsolete but conforming, so let's pick one of
1633 # those, although it makes our pages look like XHTML1 Strict.
1634 # Isn't compatibility great?
1635 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1638 $ret .= "<!doctype html>\n";
1640 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1641 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1644 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1645 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1646 foreach($wgXhtmlNamespaces as $tag => $ns) {
1647 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1649 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1653 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1654 $ret .= implode( "\n", array(
1655 $this->getHeadLinks(),
1656 $this->buildCssLinks(),
1657 $this->getHeadScripts( $sk ),
1658 $this->getHeadItems(),
1661 $ret .= Html
::inlineStyle( $sk->usercss
);
1664 if ($wgUseTrackbacks && $this->isArticleRelated())
1665 $ret .= $this->getTitle()->trackbackRDF();
1667 $ret .= "</head>\n";
1672 * gets the global variables and mScripts
1674 * also adds userjs to the end if enabled:
1676 function getHeadScripts( Skin
$sk ) {
1677 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1678 global $wgStylePath, $wgStyleVersion;
1680 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1681 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1683 //add site JS if enabled:
1684 if( $wgUseSiteJs ) {
1685 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1686 $this->addScriptFile( Skin
::makeUrl( '-',
1687 "action=raw$jsCache&gen=js&useskin=" .
1688 urlencode( $sk->getSkinName() )
1693 //add user js if enabled:
1694 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1695 $action = $wgRequest->getVal( 'action', 'view' );
1696 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1697 # XXX: additional security check/prompt?
1698 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1700 $userpage = $wgUser->getUserPage();
1701 $userjs = Skin
::makeUrl(
1702 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1703 'action=raw&ctype=' . $wgJsMimeType );
1704 $this->addScriptFile( $userjs );
1708 $scripts .= "\n" . $this->mScripts
;
1712 protected function addDefaultMeta() {
1713 global $wgVersion, $wgHtml5;
1715 static $called = false;
1717 # Don't run this twice
1723 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1725 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1727 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1728 if( $p !== 'index,follow' ) {
1729 // http://www.robotstxt.org/wc/meta-user.html
1730 // Only show if it's different from the default robots policy
1731 $this->addMeta( 'robots', $p );
1734 if ( count( $this->mKeywords
) > 0 ) {
1736 "/<.*?" . ">/" => '',
1739 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1744 * @return string HTML tag links to be put in the header.
1746 public function getHeadLinks() {
1747 global $wgRequest, $wgFeed;
1749 // Ideally this should happen earlier, somewhere. :P
1750 $this->addDefaultMeta();
1754 foreach ( $this->mMetatags
as $tag ) {
1755 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1757 $tag[0] = substr( $tag[0], 5 );
1761 $tags[] = Html
::element( 'meta',
1764 'content' => $tag[1] ) );
1766 foreach ( $this->mLinktags
as $tag ) {
1767 $tags[] = Html
::element( 'link', $tag );
1771 foreach( $this->getSyndicationLinks() as $format => $link ) {
1772 # Use the page name for the title (accessed through $wgTitle since
1773 # there's no other way). In principle, this could lead to issues
1774 # with having the same name for different feeds corresponding to
1775 # the same page, but we can't avoid that at this low a level.
1777 $tags[] = $this->feedLink(
1780 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1781 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1784 # Recent changes feed should appear on every page (except recentchanges,
1785 # that would be redundant). Put it after the per-page feed to avoid
1786 # changing existing behavior. It's still available, probably via a
1787 # menu in your browser. Some sites might have a different feed they'd
1788 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1789 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1790 # If so, use it instead.
1792 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses, $wgAdvertisedFeedTypes;
1793 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1795 if ( $wgOverrideSiteFeed ) {
1796 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1797 $tags[] = $this->feedLink (
1799 htmlspecialchars( $feedUrl ),
1800 wfMsg( "site-{$type}-feed", $wgSitename ) );
1802 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1803 foreach ( $wgAdvertisedFeedTypes as $format ) {
1804 $tags[] = $this->feedLink(
1806 $rctitle->getLocalURL( "feed={$format}" ),
1807 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1812 return implode( "\n", $tags );
1816 * Return URLs for each supported syndication format for this page.
1817 * @return array associating format keys with URLs
1819 public function getSyndicationLinks() {
1820 return $this->mFeedLinks
;
1824 * Generate a <link rel/> for an RSS feed.
1826 private function feedLink( $type, $url, $text ) {
1827 return Html
::element( 'link', array(
1828 'rel' => 'alternate',
1829 'type' => "application/$type+xml",
1835 * Add a local or specified stylesheet, with the given media options.
1836 * Meant primarily for internal use...
1838 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1839 * @param $conditional -- for IE conditional comments, specifying an IE version
1840 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1842 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1844 // Even though we expect the media type to be lowercase, but here we
1845 // force it to lowercase to be safe.
1847 $options['media'] = $media;
1849 $options['condition'] = $condition;
1851 $options['dir'] = $dir;
1852 $this->styles
[$style] = $options;
1856 * Adds inline CSS styles
1857 * @param $style_css Mixed: inline CSS
1859 public function addInlineStyle( $style_css ){
1860 $this->mScripts
.= Html
::inlineStyle( $style_css );
1864 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1865 * These will be applied to various media & IE conditionals.
1867 public function buildCssLinks() {
1869 foreach( $this->styles
as $file => $options ) {
1870 $link = $this->styleLink( $file, $options );
1875 return implode( "\n", $links );
1878 protected function styleLink( $style, $options ) {
1881 if( isset( $options['dir'] ) ) {
1883 $siteDir = $wgContLang->getDir();
1884 if( $siteDir != $options['dir'] )
1888 if( isset( $options['media'] ) ) {
1889 $media = $this->transformCssMedia( $options['media'] );
1890 if( is_null( $media ) ) {
1897 if( substr( $style, 0, 1 ) == '/' ||
1898 substr( $style, 0, 5 ) == 'http:' ||
1899 substr( $style, 0, 6 ) == 'https:' ) {
1902 global $wgStylePath, $wgStyleVersion;
1903 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1906 $link = Html
::linkedStyle( $url, $media );
1908 if( isset( $options['condition'] ) ) {
1909 $condition = htmlspecialchars( $options['condition'] );
1910 $link = "<!--[if $condition]>$link<![endif]-->";
1915 function transformCssMedia( $media ) {
1916 global $wgRequest, $wgHandheldForIPhone;
1918 // Switch in on-screen display for media testing
1920 'printable' => 'print',
1921 'handheld' => 'handheld',
1923 foreach( $switches as $switch => $targetMedia ) {
1924 if( $wgRequest->getBool( $switch ) ) {
1925 if( $media == $targetMedia ) {
1927 } elseif( $media == 'screen' ) {
1933 // Expand longer media queries as iPhone doesn't grok 'handheld'
1934 if( $wgHandheldForIPhone ) {
1935 $mediaAliases = array(
1936 'screen' => 'screen and (min-device-width: 481px)',
1937 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1940 if( isset( $mediaAliases[$media] ) ) {
1941 $media = $mediaAliases[$media];
1949 * Turn off regular page output and return an error reponse
1950 * for when rate limiting has triggered.
1952 public function rateLimited() {
1954 $this->setPageTitle(wfMsg('actionthrottled'));
1955 $this->setRobotPolicy( 'noindex,follow' );
1956 $this->setArticleRelated( false );
1957 $this->enableClientCache( false );
1958 $this->mRedirect
= '';
1960 $this->setStatusCode(503);
1961 $this->addWikiMsg( 'actionthrottledtext' );
1963 $this->returnToMain( null, $this->getTitle() );
1967 * Show an "add new section" link?
1971 public function showNewSectionLink() {
1972 return $this->mNewSectionLink
;
1976 * Forcibly hide the new section link?
1980 public function forceHideNewSectionLink() {
1981 return $this->mHideNewSectionLink
;
1985 * Show a warning about slave lag
1987 * If the lag is higher than $wgSlaveLagCritical seconds,
1988 * then the warning is a bit more obvious. If the lag is
1989 * lower than $wgSlaveLagWarning, then no warning is shown.
1991 * @param int $lag Slave lag
1993 public function showLagWarning( $lag ) {
1994 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
1995 if( $lag >= $wgSlaveLagWarning ) {
1996 $message = $lag < $wgSlaveLagCritical
1999 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2000 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2005 * Add a wikitext-formatted message to the output.
2006 * This is equivalent to:
2008 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2010 public function addWikiMsg( /*...*/ ) {
2011 $args = func_get_args();
2012 $name = array_shift( $args );
2013 $this->addWikiMsgArray( $name, $args );
2017 * Add a wikitext-formatted message to the output.
2018 * Like addWikiMsg() except the parameters are taken as an array
2019 * instead of a variable argument list.
2021 * $options is passed through to wfMsgExt(), see that function for details.
2023 public function addWikiMsgArray( $name, $args, $options = array() ) {
2024 $options[] = 'parse';
2025 $text = wfMsgExt( $name, $options, $args );
2026 $this->addHTML( $text );
2030 * This function takes a number of message/argument specifications, wraps them in
2031 * some overall structure, and then parses the result and adds it to the output.
2033 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2034 * on. The subsequent arguments may either be strings, in which case they are the
2035 * message names, or arrays, in which case the first element is the message name,
2036 * and subsequent elements are the parameters to that message.
2038 * The special named parameter 'options' in a message specification array is passed
2039 * through to the $options parameter of wfMsgExt().
2041 * Don't use this for messages that are not in users interface language.
2045 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2049 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2051 * The newline after opening div is needed in some wikitext. See bug 19226.
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 ) );