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 ) {
352 $name = $wgContLang->convert( $name, true );
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 ) { $this->mShowFeedLinks
= $show; }
398 public function setFeedAppendQuery( $val ) {
399 global $wgFeedClasses;
401 $this->mFeedLinks
= array();
403 foreach( $wgFeedClasses as $type => $class ) {
404 $query = "feed=$type&".$val;
405 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
409 public function addFeedLink( $format, $href ) {
410 $this->mFeedLinks
[$format] = $href;
413 public function isSyndicated() { return count($this->mFeedLinks
); }
415 public function setArticleRelated( $v ) {
416 $this->mIsArticleRelated
= $v;
418 $this->mIsarticle
= false;
421 public function setArticleFlag( $v ) {
422 $this->mIsarticle
= $v;
424 $this->mIsArticleRelated
= $v;
428 public function isArticleRelated() { return $this->mIsArticleRelated
; }
430 public function getLanguageLinks() { return $this->mLanguageLinks
; }
431 public function addLanguageLinks($newLinkArray) {
432 $this->mLanguageLinks +
= $newLinkArray;
434 public function setLanguageLinks($newLinkArray) {
435 $this->mLanguageLinks
= $newLinkArray;
438 public function getCategoryLinks() {
439 return $this->mCategoryLinks
;
442 public function getCategories() {
443 return $this->mCategories
;
447 * Add an array of categories, with names in the keys
449 public function addCategoryLinks( $categories ) {
450 global $wgUser, $wgContLang;
452 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
456 # Add the links to a LinkBatch
457 $arr = array( NS_CATEGORY
=> $categories );
459 $lb->setArray( $arr );
461 # Fetch existence plus the hiddencat property
462 $dbr = wfGetDB( DB_SLAVE
);
463 $pageTable = $dbr->tableName( 'page' );
464 $where = $lb->constructSet( 'page', $dbr );
465 $propsTable = $dbr->tableName( 'page_props' );
466 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
467 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
468 $res = $dbr->query( $sql, __METHOD__
);
470 # Add the results to the link cache
471 $lb->addResultToCache( LinkCache
::singleton(), $res );
473 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
474 $categories = array_combine( array_keys( $categories ),
475 array_fill( 0, count( $categories ), 'normal' ) );
477 # Mark hidden categories
478 foreach ( $res as $row ) {
479 if ( isset( $row->pp_value
) ) {
480 $categories[$row->page_title
] = 'hidden';
484 # Add the remaining categories to the skin
485 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
486 $sk = $wgUser->getSkin();
487 foreach ( $categories as $category => $type ) {
488 $origcategory = $category;
489 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
490 $wgContLang->findVariantLink( $category, $title, true );
491 if ( $category != $origcategory )
492 if ( array_key_exists( $category, $categories ) )
494 $text = $wgContLang->convertHtml( $title->getText() );
495 $this->mCategories
[] = $title->getText();
496 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
501 public function setCategoryLinks($categories) {
502 $this->mCategoryLinks
= array();
503 $this->addCategoryLinks($categories);
506 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
507 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
509 public function disallowUserJs() { $this->mAllowUserJs
= false; }
510 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
512 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
513 public function addHTML( $text ) { $this->mBodytext
.= $text; }
514 public function clearHTML() { $this->mBodytext
= ''; }
515 public function getHTML() { return $this->mBodytext
; }
516 public function debug( $text ) { $this->mDebugtext
.= $text; }
519 public function setParserOptions( $options ) {
520 wfDeprecated( __METHOD__
);
521 return $this->parserOptions( $options );
524 public function parserOptions( $options = null ) {
525 if ( !$this->mParserOptions
) {
526 $this->mParserOptions
= new ParserOptions
;
528 return wfSetVar( $this->mParserOptions
, $options );
532 * Set the revision ID which will be seen by the wiki text parser
533 * for things such as embedded {{REVISIONID}} variable use.
534 * @param mixed $revid an integer, or NULL
535 * @return mixed previous value
537 public function setRevisionId( $revid ) {
538 $val = is_null( $revid ) ?
null : intval( $revid );
539 return wfSetVar( $this->mRevisionId
, $val );
542 public function getRevisionId() {
543 return $this->mRevisionId
;
547 * Convert wikitext to HTML and add it to the buffer
548 * Default assumes that the current page title will
551 * @param string $text
552 * @param bool $linestart
554 public function addWikiText( $text, $linestart = true ) {
555 $title = $this->getTitle(); // Work arround E_STRICT
556 $this->addWikiTextTitle( $text, $title, $linestart );
559 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
560 $this->addWikiTextTitle($text, $title, $linestart);
563 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
564 $this->addWikiTextTitle( $text, $title, $linestart, true );
567 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
570 wfProfileIn( __METHOD__
);
572 wfIncrStats( 'pcache_not_possible' );
574 $popts = $this->parserOptions();
575 $oldTidy = $popts->setTidy( $tidy );
577 $parserOutput = $wgParser->parse( $text, $title, $popts,
578 $linestart, true, $this->mRevisionId
);
580 $popts->setTidy( $oldTidy );
582 $this->addParserOutput( $parserOutput );
584 wfProfileOut( __METHOD__
);
589 * @param ParserOutput object &$parserOutput
591 public function addParserOutputNoText( &$parserOutput ) {
592 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
594 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
595 $this->addCategoryLinks( $parserOutput->getCategories() );
596 $this->mNewSectionLink
= $parserOutput->getNewSection();
597 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
599 $this->mParseWarnings
= $parserOutput->getWarnings();
600 if ( $parserOutput->getCacheTime() == -1 ) {
601 $this->enableClientCache( false );
603 $this->mNoGallery
= $parserOutput->getNoGallery();
604 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
606 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
607 if ( isset( $this->mTemplateIds
[$ns] ) ) {
608 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
610 $this->mTemplateIds
[$ns] = $dbks;
614 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
615 $this->setPageTitle( $dt );
616 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
617 $this->setPageTitle( $title );
619 // Hooks registered in the object
620 global $wgParserOutputHooks;
621 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
622 list( $hookName, $data ) = $hookInfo;
623 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
624 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
628 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
633 * @param ParserOutput &$parserOutput
635 function addParserOutput( &$parserOutput ) {
636 $this->addParserOutputNoText( $parserOutput );
637 $text = $parserOutput->getText();
638 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
639 $this->addHTML( $text );
643 * Add wikitext to the buffer, assuming that this is the primary text for a page view
644 * Saves the text into the parser cache if possible.
646 * @param string $text
647 * @param Article $article
649 * @deprecated Use Article::outputWikitext
651 public function addPrimaryWikiText( $text, $article, $cache = true ) {
654 wfDeprecated( __METHOD__
);
656 $popts = $this->parserOptions();
657 $popts->setTidy(true);
658 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
659 $popts, true, true, $this->mRevisionId
);
660 $popts->setTidy(false);
661 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
662 $parserCache = ParserCache
::singleton();
663 $parserCache->save( $parserOutput, $article, $popts);
666 $this->addParserOutput( $parserOutput );
670 * @deprecated use addWikiTextTidy()
672 public function addSecondaryWikiText( $text, $linestart = true ) {
673 wfDeprecated( __METHOD__
);
674 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
678 * Add wikitext with tidy enabled
680 public function addWikiTextTidy( $text, $linestart = true ) {
681 $title = $this->getTitle();
682 $this->addWikiTextTitleTidy($text, $title, $linestart);
687 * Add the output of a QuickTemplate to the output buffer
689 * @param QuickTemplate $template
691 public function addTemplate( &$template ) {
693 $template->execute();
694 $this->addHTML( ob_get_contents() );
699 * Parse wikitext and return the HTML.
701 * @param string $text
702 * @param bool $linestart Is this the start of a line?
703 * @param bool $interface ??
705 public function parse( $text, $linestart = true, $interface = false ) {
707 if( is_null( $this->getTitle() ) ) {
708 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
710 $popts = $this->parserOptions();
711 if ( $interface) { $popts->setInterfaceMessage(true); }
712 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
713 $linestart, true, $this->mRevisionId
);
714 if ( $interface) { $popts->setInterfaceMessage(false); }
715 return $parserOutput->getText();
718 /** Parse wikitext, strip paragraphs, and return the HTML. */
719 public function parseInline( $text, $linestart = true, $interface = false ) {
720 $parsed = $this->parse( $text, $linestart, $interface );
723 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
731 * @param Article $article
736 * @return bool True if successful, else false.
738 public function tryParserCache( &$article ) {
739 wfDeprecated( __METHOD__
);
740 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
742 if ($parserOutput !== false) {
743 $this->addParserOutput( $parserOutput );
751 * @param int $maxage Maximum cache time on the Squid, in seconds.
753 public function setSquidMaxage( $maxage ) {
754 $this->mSquidMaxage
= $maxage;
758 * Use enableClientCache(false) to force it to send nocache headers
761 public function enableClientCache( $state ) {
762 return wfSetVar( $this->mEnableClientCache
, $state );
765 function getCacheVaryCookies() {
766 global $wgCookiePrefix, $wgCacheVaryCookies;
768 if ( $cookies === null ) {
769 $cookies = array_merge(
771 "{$wgCookiePrefix}Token",
772 "{$wgCookiePrefix}LoggedOut",
777 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
782 function uncacheableBecauseRequestVars() {
784 return $wgRequest->getText('useskin', false) === false
785 && $wgRequest->getText('uselang', false) === false;
789 * Check if the request has a cache-varying cookie header
790 * If it does, it's very important that we don't allow public caching
792 function haveCacheVaryCookies() {
794 $cookieHeader = $wgRequest->getHeader( 'cookie' );
795 if ( $cookieHeader === false ) {
798 $cvCookies = $this->getCacheVaryCookies();
799 foreach ( $cvCookies as $cookieName ) {
800 # Check for a simple string match, like the way squid does it
801 if ( strpos( $cookieHeader, $cookieName ) ) {
802 wfDebug( __METHOD__
.": found $cookieName\n" );
806 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
810 public function addVaryHeader( $header, $option = null ) {
811 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
812 $this->mVaryHeader
[$header] = $option;
814 elseif( is_array( $option ) ) {
815 if( is_array( $this->mVaryHeader
[$header] ) ) {
816 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
819 $this->mVaryHeader
[$header] = $option;
822 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
825 /** Get a complete X-Vary-Options header */
826 public function getXVO() {
827 $cvCookies = $this->getCacheVaryCookies();
829 $cookiesOption = array();
830 foreach ( $cvCookies as $cookieName ) {
831 $cookiesOption[] = 'string-contains=' . $cookieName;
833 $this->addVaryHeader( 'Cookie', $cookiesOption );
836 foreach( $this->mVaryHeader
as $header => $option ) {
837 $newheader = $header;
838 if( is_array( $option ) )
839 $newheader .= ';' . implode( ';', $option );
840 $headers[] = $newheader;
842 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
847 public function sendCacheControl() {
848 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
850 $response = $wgRequest->response();
851 if ($wgUseETag && $this->mETag
)
852 $response->header("ETag: $this->mETag");
854 # don't serve compressed data to clients who can't handle it
855 # maintain different caches for logged-in users and non-logged in ones
856 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
859 # Add an X-Vary-Options header for Squid with Wikimedia patches
860 $response->header( $this->getXVO() );
863 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
864 if( $wgUseSquid && session_id() == '' &&
865 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
868 # We'll purge the proxy cache explicitly, but require end user agents
869 # to revalidate against the proxy on each visit.
870 # Surrogate-Control controls our Squid, Cache-Control downstream caches
871 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
872 # start with a shorter timeout for initial testing
873 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
874 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
875 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
877 # We'll purge the proxy cache for anons explicitly, but require end user agents
878 # to revalidate against the proxy on each visit.
879 # IMPORTANT! The Squid needs to replace the Cache-Control header with
880 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
881 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
882 # start with a shorter timeout for initial testing
883 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
884 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
887 # We do want clients to cache if they can, but they *must* check for updates
888 # on revisiting the page.
889 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
890 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
891 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
893 if($this->mLastModified
) {
894 $response->header( "Last-Modified: {$this->mLastModified}" );
897 wfDebug( __METHOD__
. ": no caching **\n", false );
899 # In general, the absence of a last modified header should be enough to prevent
900 # the client from using its cache. We send a few other things just to make sure.
901 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
902 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
903 $response->header( 'Pragma: no-cache' );
905 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
909 * Get the message associed with the HTTP response code $code
911 * @param $code Integer: status code
912 * @return String or null: message or null if $code is not in the list of
915 public static function getStatusMessage( $code ) {
916 static $statusMessage = array(
918 101 => 'Switching Protocols',
923 203 => 'Non-Authoritative Information',
925 205 => 'Reset Content',
926 206 => 'Partial Content',
927 207 => 'Multi-Status',
928 300 => 'Multiple Choices',
929 301 => 'Moved Permanently',
932 304 => 'Not Modified',
934 307 => 'Temporary Redirect',
935 400 => 'Bad Request',
936 401 => 'Unauthorized',
937 402 => 'Payment Required',
940 405 => 'Method Not Allowed',
941 406 => 'Not Acceptable',
942 407 => 'Proxy Authentication Required',
943 408 => 'Request Timeout',
946 411 => 'Length Required',
947 412 => 'Precondition Failed',
948 413 => 'Request Entity Too Large',
949 414 => 'Request-URI Too Large',
950 415 => 'Unsupported Media Type',
951 416 => 'Request Range Not Satisfiable',
952 417 => 'Expectation Failed',
953 422 => 'Unprocessable Entity',
955 424 => 'Failed Dependency',
956 500 => 'Internal Server Error',
957 501 => 'Not Implemented',
958 502 => 'Bad Gateway',
959 503 => 'Service Unavailable',
960 504 => 'Gateway Timeout',
961 505 => 'HTTP Version Not Supported',
962 507 => 'Insufficient Storage'
964 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
968 * Finally, all the text has been munged and accumulated into
969 * the object, let's actually output it:
971 public function output() {
972 global $wgUser, $wgOutputEncoding, $wgRequest;
973 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
974 global $wgUseAjax, $wgAjaxWatch;
975 global $wgEnableMWSuggest, $wgUniversalEditButton;
978 if( $this->mDoNothing
){
981 wfProfileIn( __METHOD__
);
982 if ( '' != $this->mRedirect
) {
983 # Standards require redirect URLs to be absolute
984 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
985 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
986 if( !$wgDebugRedirects ) {
987 $message = self
::getStatusMessage( $this->mRedirectCode
);
988 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
990 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
992 $this->sendCacheControl();
994 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
995 if( $wgDebugRedirects ) {
996 $url = htmlspecialchars( $this->mRedirect
);
997 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
998 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
999 print "</body>\n</html>\n";
1001 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1003 wfProfileOut( __METHOD__
);
1005 } elseif ( $this->mStatusCode
) {
1006 $message = self
::getStatusMessage( $this->mStatusCode
);
1008 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1011 $sk = $wgUser->getSkin();
1014 $this->addScriptFile( 'ajax.js' );
1016 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1018 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1019 $this->addScriptFile( 'ajaxwatch.js' );
1022 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1023 $this->addScriptFile( 'mwsuggest.js' );
1027 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1028 $this->addScriptFile( 'rightclickedit.js' );
1031 if( $wgUniversalEditButton ) {
1032 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1033 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1034 // Original UniversalEditButton
1035 $msg = wfMsg('edit');
1036 $this->addLink( array(
1037 'rel' => 'alternate',
1038 'type' => 'application/x-wiki',
1040 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1042 // Alternate edit link
1043 $this->addLink( array(
1046 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1051 # Buffer output; final headers may depend on later processing
1054 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1055 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1057 if ($this->mArticleBodyOnly
) {
1058 $this->out($this->mBodytext
);
1060 // Hook that allows last minute changes to the output page, e.g.
1061 // adding of CSS or Javascript by extensions.
1062 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1064 wfProfileIn( 'Output-skin' );
1065 $sk->outputPage( $this );
1066 wfProfileOut( 'Output-skin' );
1069 $this->sendCacheControl();
1071 wfProfileOut( __METHOD__
);
1075 * Actually output something with print(). Performs an iconv to the
1076 * output encoding, if needed.
1077 * @param string $ins The string to output
1079 public function out( $ins ) {
1080 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1081 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1084 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1085 if ( false === $outs ) { $outs = $ins; }
1093 public static function setEncodings() {
1094 global $wgInputEncoding, $wgOutputEncoding;
1097 $wgInputEncoding = strtolower( $wgInputEncoding );
1099 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1100 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1103 $wgOutputEncoding = $wgInputEncoding;
1107 * Deprecated, use wfReportTime() instead.
1111 public function reportTime() {
1112 wfDeprecated( __METHOD__
);
1113 $time = wfReportTime();
1118 * Produce a "user is blocked" page.
1120 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1123 function blockedPage( $return = true ) {
1124 global $wgUser, $wgContLang, $wgLang;
1126 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1127 $this->setRobotPolicy( 'noindex,nofollow' );
1128 $this->setArticleRelated( false );
1130 $name = User
::whoIs( $wgUser->blockedBy() );
1131 $reason = $wgUser->blockedFor();
1132 if( $reason == '' ) {
1133 $reason = wfMsg( 'blockednoreason' );
1135 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1138 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1140 $blockid = $wgUser->mBlock
->mId
;
1142 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1143 if ( $blockExpiry == 'infinity' ) {
1144 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1145 // Search for localization in 'ipboptions'
1146 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1147 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1148 if ( strpos( $option, ":" ) === false )
1150 list( $show, $value ) = explode( ":", $option );
1151 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1152 $blockExpiry = $show;
1157 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1160 if ( $wgUser->mBlock
->mAuto
) {
1161 $msg = 'autoblockedtext';
1163 $msg = 'blockedtext';
1166 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1167 * This could be a username, an ip range, or a single ip. */
1168 $intended = $wgUser->mBlock
->mAddress
;
1170 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1172 # Don't auto-return to special pages
1174 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1175 $this->returnToMain( null, $return );
1180 * Output a standard error page
1182 * @param string $title Message key for page title
1183 * @param string $msg Message key for page text
1184 * @param array $params Message parameters
1186 public function showErrorPage( $title, $msg, $params = array() ) {
1187 if ( $this->getTitle() ) {
1188 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1190 $this->setPageTitle( wfMsg( $title ) );
1191 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1192 $this->setRobotPolicy( 'noindex,nofollow' );
1193 $this->setArticleRelated( false );
1194 $this->enableClientCache( false );
1195 $this->mRedirect
= '';
1196 $this->mBodytext
= '';
1198 array_unshift( $params, 'parse' );
1199 array_unshift( $params, $msg );
1200 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1202 $this->returnToMain();
1206 * Output a standard permission error page
1208 * @param array $errors Error message keys
1210 public function showPermissionsErrorPage( $errors, $action = null )
1212 $this->mDebugtext
.= 'Original title: ' .
1213 $this->getTitle()->getPrefixedText() . "\n";
1214 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1215 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1216 $this->setRobotPolicy( 'noindex,nofollow' );
1217 $this->setArticleRelated( false );
1218 $this->enableClientCache( false );
1219 $this->mRedirect
= '';
1220 $this->mBodytext
= '';
1221 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1225 public function errorpage( $title, $msg ) {
1226 wfDeprecated( __METHOD__
);
1227 throw new ErrorPageError( $title, $msg );
1231 * Display an error page indicating that a given version of MediaWiki is
1232 * required to use it
1234 * @param mixed $version The version of MediaWiki needed to use the page
1236 public function versionRequired( $version ) {
1237 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1238 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1239 $this->setRobotPolicy( 'noindex,nofollow' );
1240 $this->setArticleRelated( false );
1241 $this->mBodytext
= '';
1243 $this->addWikiMsg( 'versionrequiredtext', $version );
1244 $this->returnToMain();
1248 * Display an error page noting that a given permission bit is required.
1250 * @param string $permission key required
1252 public function permissionRequired( $permission ) {
1255 $this->setPageTitle( wfMsg( 'badaccess' ) );
1256 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1257 $this->setRobotPolicy( 'noindex,nofollow' );
1258 $this->setArticleRelated( false );
1259 $this->mBodytext
= '';
1261 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1262 User
::getGroupsWithPermission( $permission ) );
1264 $this->addWikiMsg( 'badaccess-groups',
1265 $wgLang->commaList( $groups ),
1268 $this->addWikiMsg( 'badaccess-group0' );
1270 $this->returnToMain();
1274 * Use permissionRequired.
1277 public function sysopRequired() {
1278 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1282 * Use permissionRequired.
1285 public function developerRequired() {
1286 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1290 * Produce the stock "please login to use the wiki" page
1292 public function loginToUse() {
1293 global $wgUser, $wgContLang;
1295 if( $wgUser->isLoggedIn() ) {
1296 $this->permissionRequired( 'read' );
1300 $skin = $wgUser->getSkin();
1302 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1303 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1304 $this->setRobotPolicy( 'noindex,nofollow' );
1305 $this->setArticleFlag( false );
1307 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1308 $loginLink = $skin->link(
1310 wfMsgHtml( 'loginreqlink' ),
1312 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1313 array( 'known', 'noclasses' )
1315 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1316 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1318 # Don't return to the main page if the user can't read it
1319 # otherwise we'll end up in a pointless loop
1320 $mainPage = Title
::newMainPage();
1321 if( $mainPage->userCanRead() )
1322 $this->returnToMain( null, $mainPage );
1326 public function databaseError( $fname, $sql, $error, $errno ) {
1327 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1331 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1332 * @return string The wikitext error-messages, formatted into a list.
1334 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1335 if ($action == null) {
1336 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1339 $action_desc = wfMsgNoTrans( "action-$action" );
1340 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1343 if (count( $errors ) > 1) {
1344 $text .= '<ul class="permissions-errors">' . "\n";
1346 foreach( $errors as $error )
1349 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1354 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1361 * Display a page stating that the Wiki is in read-only mode,
1362 * and optionally show the source of the page that the user
1363 * was trying to edit. Should only be called (for this
1364 * purpose) after wfReadOnly() has returned true.
1366 * For historical reasons, this function is _also_ used to
1367 * show the error message when a user tries to edit a page
1368 * they are not allowed to edit. (Unless it's because they're
1369 * blocked, then we show blockedPage() instead.) In this
1370 * case, the second parameter should be set to true and a list
1371 * of reasons supplied as the third parameter.
1373 * @todo Needs to be split into multiple functions.
1375 * @param string $source Source code to show (or null).
1376 * @param bool $protected Is this a permissions error?
1377 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1379 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1381 $skin = $wgUser->getSkin();
1383 $this->setRobotPolicy( 'noindex,nofollow' );
1384 $this->setArticleRelated( false );
1386 // If no reason is given, just supply a default "I can't let you do
1387 // that, Dave" message. Should only occur if called by legacy code.
1388 if ( $protected && empty($reasons) ) {
1389 $reasons[] = array( 'badaccess-group0' );
1392 if ( !empty($reasons) ) {
1393 // Permissions error
1395 $this->setPageTitle( wfMsg( 'viewsource' ) );
1404 array( 'known', 'noclasses' )
1409 $this->setPageTitle( wfMsg( 'badaccess' ) );
1411 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1413 // Wiki is read only
1414 $this->setPageTitle( wfMsg( 'readonly' ) );
1415 $reason = wfReadOnlyReason();
1416 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1419 // Show source, if supplied
1420 if( is_string( $source ) ) {
1421 $this->addWikiMsg( 'viewsourcetext' );
1424 'id' => 'wpTextbox1',
1425 'name' => 'wpTextbox1',
1426 'cols' => $wgUser->getOption( 'cols' ),
1427 'rows' => $wgUser->getOption( 'rows' ),
1428 'readonly' => 'readonly'
1430 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1432 // Show templates used by this article
1433 $skin = $wgUser->getSkin();
1434 $article = new Article( $this->getTitle() );
1435 $this->addHTML( "<div class='templatesUsed'>
1436 {$skin->formatTemplates( $article->getUsedTemplates() )}
1441 # If the title doesn't exist, it's fairly pointless to print a return
1442 # link to it. After all, you just tried editing it and couldn't, so
1443 # what's there to do there?
1444 if( $this->getTitle()->exists() ) {
1445 $this->returnToMain( null, $this->getTitle() );
1450 public function fatalError( $message ) {
1451 wfDeprecated( __METHOD__
);
1452 throw new FatalError( $message );
1456 public function unexpectedValueError( $name, $val ) {
1457 wfDeprecated( __METHOD__
);
1458 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1462 public function fileCopyError( $old, $new ) {
1463 wfDeprecated( __METHOD__
);
1464 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1468 public function fileRenameError( $old, $new ) {
1469 wfDeprecated( __METHOD__
);
1470 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1474 public function fileDeleteError( $name ) {
1475 wfDeprecated( __METHOD__
);
1476 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1480 public function fileNotFoundError( $name ) {
1481 wfDeprecated( __METHOD__
);
1482 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1485 public function showFatalError( $message ) {
1486 $this->setPageTitle( wfMsg( "internalerror" ) );
1487 $this->setRobotPolicy( "noindex,nofollow" );
1488 $this->setArticleRelated( false );
1489 $this->enableClientCache( false );
1490 $this->mRedirect
= '';
1491 $this->mBodytext
= $message;
1494 public function showUnexpectedValueError( $name, $val ) {
1495 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1498 public function showFileCopyError( $old, $new ) {
1499 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1502 public function showFileRenameError( $old, $new ) {
1503 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1506 public function showFileDeleteError( $name ) {
1507 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1510 public function showFileNotFoundError( $name ) {
1511 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1515 * Add a "return to" link pointing to a specified title
1517 * @param Title $title Title to link
1518 * @param string $query Query string
1520 public function addReturnTo( $title, $query = array() ) {
1522 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1523 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1524 $title, null, array(), $query ) );
1525 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1529 * Add a "return to" link pointing to a specified title,
1530 * or the title indicated in the request, or else the main page
1532 * @param null $unused No longer used
1533 * @param Title $returnto Title to return to
1535 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1538 if ( $returnto == null ) {
1539 $returnto = $wgRequest->getText( 'returnto' );
1542 if ( $returntoquery == null ) {
1543 $returntoquery = $wgRequest->getText( 'returntoquery' );
1546 if ( '' === $returnto ) {
1547 $returnto = Title
::newMainPage();
1550 if ( is_object( $returnto ) ) {
1551 $titleObj = $returnto;
1553 $titleObj = Title
::newFromText( $returnto );
1555 if ( !is_object( $titleObj ) ) {
1556 $titleObj = Title
::newMainPage();
1559 $this->addReturnTo( $titleObj, $returntoquery );
1563 * @return string The doctype, opening <html>, and head element.
1565 * @param $sk Skin The given Skin
1567 public function headElement( Skin
$sk, $includeStyle = true ) {
1568 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1569 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1570 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5;
1572 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1573 if ( $sk->commonPrintStylesheet() ) {
1574 $this->addStyle( 'common/wikiprintable.css', 'print' );
1576 $sk->setupUserCss( $this );
1580 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1581 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1584 if ( '' == $this->getHTMLTitle() ) {
1585 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1588 $dir = $wgContLang->getDir();
1591 $ret .= "<!DOCTYPE html>\n";
1592 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1593 if ($wgHtml5Version) $ret .= " version=\"$wgHtml5Version\" ";
1596 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1597 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1598 foreach($wgXhtmlNamespaces as $tag => $ns) {
1599 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1601 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1605 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1606 $ret .= implode( "\n", array(
1607 $this->getHeadLinks(),
1608 $this->buildCssLinks(),
1609 $this->getHeadScripts( $sk ),
1610 $this->getHeadItems(),
1613 $ret .= Html
::inlineStyle( $sk->usercss
);
1616 if ($wgUseTrackbacks && $this->isArticleRelated())
1617 $ret .= $this->getTitle()->trackbackRDF();
1619 $ret .= "</head>\n";
1624 * gets the global variables and mScripts
1626 * also adds userjs to the end if enabled:
1628 function getHeadScripts( Skin
$sk ) {
1629 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1630 global $wgStylePath, $wgStyleVersion;
1632 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1633 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1635 //add site JS if enabled:
1636 if( $wgUseSiteJs ) {
1637 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1638 $this->addScriptFile( Skin
::makeUrl( '-',
1639 "action=raw$jsCache&gen=js&useskin=" .
1640 urlencode( $sk->getSkinName() )
1645 //add user js if enabled:
1646 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1647 $action = $wgRequest->getVal( 'action', 'view' );
1648 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1649 # XXX: additional security check/prompt?
1650 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1652 $userpage = $wgUser->getUserPage();
1653 $userjs = Skin
::makeUrl(
1654 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1655 'action=raw&ctype=' . $wgJsMimeType );
1656 $this->addScriptFile( $userjs );
1660 $scripts .= "\n" . $this->mScripts
;
1664 protected function addDefaultMeta() {
1665 global $wgVersion, $wgHtml5;
1667 static $called = false;
1669 # Don't run this twice
1675 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1677 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1679 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1680 if( $p !== 'index,follow' ) {
1681 // http://www.robotstxt.org/wc/meta-user.html
1682 // Only show if it's different from the default robots policy
1683 $this->addMeta( 'robots', $p );
1686 if ( count( $this->mKeywords
) > 0 ) {
1688 "/<.*?" . ">/" => '',
1691 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1696 * @return string HTML tag links to be put in the header.
1698 public function getHeadLinks() {
1699 global $wgRequest, $wgFeed;
1701 // Ideally this should happen earlier, somewhere. :P
1702 $this->addDefaultMeta();
1706 foreach ( $this->mMetatags
as $tag ) {
1707 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1709 $tag[0] = substr( $tag[0], 5 );
1713 $tags[] = Html
::element( 'meta',
1716 'content' => $tag[1] ) );
1718 foreach ( $this->mLinktags
as $tag ) {
1719 $tags[] = Html
::element( 'link', $tag );
1723 foreach( $this->getSyndicationLinks() as $format => $link ) {
1724 # Use the page name for the title (accessed through $wgTitle since
1725 # there's no other way). In principle, this could lead to issues
1726 # with having the same name for different feeds corresponding to
1727 # the same page, but we can't avoid that at this low a level.
1729 $tags[] = $this->feedLink(
1732 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1735 # Recent changes feed should appear on every page (except recentchanges,
1736 # that would be redundant). Put it after the per-page feed to avoid
1737 # changing existing behavior. It's still available, probably via a
1738 # menu in your browser. Some sites might have a different feed they'd
1739 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1740 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1741 # If so, use it instead.
1743 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1744 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1746 if ( $wgOverrideSiteFeed ) {
1747 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1748 $tags[] = $this->feedLink (
1750 htmlspecialchars( $feedUrl ),
1751 wfMsg( "site-{$type}-feed", $wgSitename ) );
1754 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1755 foreach( $wgFeedClasses as $format => $class ) {
1756 $tags[] = $this->feedLink(
1758 $rctitle->getLocalURL( "feed={$format}" ),
1759 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1764 return implode( "\n", $tags );
1768 * Return URLs for each supported syndication format for this page.
1769 * @return array associating format keys with URLs
1771 public function getSyndicationLinks() {
1772 return $this->mFeedLinks
;
1776 * Generate a <link rel/> for an RSS feed.
1778 private function feedLink( $type, $url, $text ) {
1779 return Html
::element( 'link', array(
1780 'rel' => 'alternate',
1781 'type' => "application/$type+xml",
1787 * Add a local or specified stylesheet, with the given media options.
1788 * Meant primarily for internal use...
1790 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1791 * @param $conditional -- for IE conditional comments, specifying an IE version
1792 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1794 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1796 // Even though we expect the media type to be lowercase, but here we
1797 // force it to lowercase to be safe.
1799 $options['media'] = $media;
1801 $options['condition'] = $condition;
1803 $options['dir'] = $dir;
1804 $this->styles
[$style] = $options;
1808 * Adds inline CSS styles
1809 * @param $style_css Mixed: inline CSS
1811 public function addInlineStyle( $style_css ){
1812 $this->mScripts
.= Html
::inlineStyle( $style_css );
1816 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1817 * These will be applied to various media & IE conditionals.
1819 public function buildCssLinks() {
1821 foreach( $this->styles
as $file => $options ) {
1822 $link = $this->styleLink( $file, $options );
1827 return implode( "\n", $links );
1830 protected function styleLink( $style, $options ) {
1833 if( isset( $options['dir'] ) ) {
1835 $siteDir = $wgContLang->getDir();
1836 if( $siteDir != $options['dir'] )
1840 if( isset( $options['media'] ) ) {
1841 $media = $this->transformCssMedia( $options['media'] );
1842 if( is_null( $media ) ) {
1849 if( substr( $style, 0, 1 ) == '/' ||
1850 substr( $style, 0, 5 ) == 'http:' ||
1851 substr( $style, 0, 6 ) == 'https:' ) {
1854 global $wgStylePath, $wgStyleVersion;
1855 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1858 $link = Html
::linkedStyle( $url, $media );
1860 if( isset( $options['condition'] ) ) {
1861 $condition = htmlspecialchars( $options['condition'] );
1862 $link = "<!--[if $condition]>$link<![endif]-->";
1867 function transformCssMedia( $media ) {
1868 global $wgRequest, $wgHandheldForIPhone;
1870 // Switch in on-screen display for media testing
1872 'printable' => 'print',
1873 'handheld' => 'handheld',
1875 foreach( $switches as $switch => $targetMedia ) {
1876 if( $wgRequest->getBool( $switch ) ) {
1877 if( $media == $targetMedia ) {
1879 } elseif( $media == 'screen' ) {
1885 // Expand longer media queries as iPhone doesn't grok 'handheld'
1886 if( $wgHandheldForIPhone ) {
1887 $mediaAliases = array(
1888 'screen' => 'screen and (min-device-width: 481px)',
1889 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1892 if( isset( $mediaAliases[$media] ) ) {
1893 $media = $mediaAliases[$media];
1901 * Turn off regular page output and return an error reponse
1902 * for when rate limiting has triggered.
1904 public function rateLimited() {
1906 $this->setPageTitle(wfMsg('actionthrottled'));
1907 $this->setRobotPolicy( 'noindex,follow' );
1908 $this->setArticleRelated( false );
1909 $this->enableClientCache( false );
1910 $this->mRedirect
= '';
1912 $this->setStatusCode(503);
1913 $this->addWikiMsg( 'actionthrottledtext' );
1915 $this->returnToMain( null, $this->getTitle() );
1919 * Show an "add new section" link?
1923 public function showNewSectionLink() {
1924 return $this->mNewSectionLink
;
1928 * Forcibly hide the new section link?
1932 public function forceHideNewSectionLink() {
1933 return $this->mHideNewSectionLink
;
1937 * Show a warning about slave lag
1939 * If the lag is higher than $wgSlaveLagCritical seconds,
1940 * then the warning is a bit more obvious. If the lag is
1941 * lower than $wgSlaveLagWarning, then no warning is shown.
1943 * @param int $lag Slave lag
1945 public function showLagWarning( $lag ) {
1946 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
1947 if( $lag >= $wgSlaveLagWarning ) {
1948 $message = $lag < $wgSlaveLagCritical
1951 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
1952 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
1957 * Add a wikitext-formatted message to the output.
1958 * This is equivalent to:
1960 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1962 public function addWikiMsg( /*...*/ ) {
1963 $args = func_get_args();
1964 $name = array_shift( $args );
1965 $this->addWikiMsgArray( $name, $args );
1969 * Add a wikitext-formatted message to the output.
1970 * Like addWikiMsg() except the parameters are taken as an array
1971 * instead of a variable argument list.
1973 * $options is passed through to wfMsgExt(), see that function for details.
1975 public function addWikiMsgArray( $name, $args, $options = array() ) {
1976 $options[] = 'parse';
1977 $text = wfMsgExt( $name, $options, $args );
1978 $this->addHTML( $text );
1982 * This function takes a number of message/argument specifications, wraps them in
1983 * some overall structure, and then parses the result and adds it to the output.
1985 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1986 * on. The subsequent arguments may either be strings, in which case they are the
1987 * message names, or arrays, in which case the first element is the message name,
1988 * and subsequent elements are the parameters to that message.
1990 * The special named parameter 'options' in a message specification array is passed
1991 * through to the $options parameter of wfMsgExt().
1993 * Don't use this for messages that are not in users interface language.
1997 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2001 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2003 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2004 $msgSpecs = func_get_args();
2005 array_shift( $msgSpecs );
2006 $msgSpecs = array_values( $msgSpecs );
2008 foreach ( $msgSpecs as $n => $spec ) {
2010 if ( is_array( $spec ) ) {
2012 $name = array_shift( $args );
2013 if ( isset( $args['options'] ) ) {
2014 $options = $args['options'];
2015 unset( $args['options'] );
2021 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2023 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );