2 if ( ! defined( 'MEDIAWIKI' ) )
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mLanguageLinks = array();
16 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
17 var $mTemplateIds = array();
20 var $mSuppressQuickbar = false;
21 var $mOnloadHandler = '';
22 var $mDoNothing = false;
23 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
24 var $mIsArticleRelated = true;
25 protected $mParserOptions = null; // lazy initialised, use parserOptions()
26 var $mShowFeedLinks = false;
27 var $mFeedLinksAppendQuery = false;
28 var $mEnableClientCache = true;
29 var $mArticleBodyOnly = false;
31 var $mNewSectionLink = false;
32 var $mNoGallery = false;
33 var $mPageTitleActionText = '';
34 var $mParseWarnings = array();
35 var $mSquidMaxage = 0;
36 var $mRevisionId = null;
39 * An array of stylesheet filenames (relative from skins path), with options
40 * for CSS media, IE conditions, and RTL/LTR direction.
41 * For internal use; add settings in the skin via $this->addStyle()
43 var $styles = array();
45 private $mIndexPolicy = 'index';
46 private $mFollowPolicy = 'follow';
50 * Initialise private variables
52 function __construct() {
53 global $wgAllowUserJs;
54 $this->mAllowUserJs
= $wgAllowUserJs;
57 public function redirect( $url, $responsecode = '302' ) {
58 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
59 $this->mRedirect
= str_replace( "\n", '', $url );
60 $this->mRedirectCode
= $responsecode;
63 public function getRedirect() {
64 return $this->mRedirect
;
68 * Set the HTTP status code to send with the output.
70 * @param int $statusCode
73 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
76 * Add a new <meta> tag
77 * To add an http-equiv meta tag, precede the name with "http:"
79 * @param $name tag name
80 * @param $val tag value
82 function addMeta( $name, $val ) {
83 array_push( $this->mMetatags
, array( $name, $val ) );
86 function addKeyword( $text ) { array_push( $this->mKeywords
, $text ); }
87 function addScript( $script ) { $this->mScripts
.= "\t\t".$script; }
89 function addExtensionStyle( $url ) {
90 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
91 array_push( $this->mExtStyles
, $linkarr );
95 * Add a JavaScript file out of skins/common, or a given relative path.
96 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
98 function addScriptFile( $file ) {
99 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
100 if( substr( $file, 0, 1 ) == '/' ) {
103 $path = "{$wgStylePath}/common/{$file}";
105 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"$path?$wgStyleVersion\"></script>\n" );
109 * Add a self-contained script tag with the given contents
110 * @param string $script JavaScript text, no <script> tags
112 function addInlineScript( $script ) {
113 global $wgJsMimeType;
114 $this->mScripts
.= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
117 function getScript() {
118 return $this->mScripts
. $this->getHeadItems();
121 function getHeadItems() {
123 foreach ( $this->mHeadItems
as $item ) {
129 function addHeadItem( $name, $value ) {
130 $this->mHeadItems
[$name] = $value;
133 function hasHeadItem( $name ) {
134 return isset( $this->mHeadItems
[$name] );
137 function setETag($tag) { $this->mETag
= $tag; }
138 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
139 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly
; }
141 function addLink( $linkarr ) {
142 # $linkarr should be an associative array of attributes. We'll escape on output.
143 array_push( $this->mLinktags
, $linkarr );
146 # Get all links added by extensions
147 function getExtStyle() {
148 return $this->mExtStyles
;
151 function addMetadataLink( $linkarr ) {
152 # note: buggy CC software only reads first "meta" link
153 static $haveMeta = false;
154 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
155 $this->addLink( $linkarr );
160 * checkLastModified tells the client to use the client-cached page if
161 * possible. If sucessful, the OutputPage is disabled so that
162 * any future call to OutputPage->output() have no effect.
164 * Side effect: sets mLastModified for Last-Modified header
166 * @return bool True iff cache-ok headers was sent.
168 function checkLastModified ( $timestamp ) {
169 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
171 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
172 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
175 if( !$wgCachePages ) {
176 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
179 if( $wgUser->getOption( 'nocache' ) ) {
180 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
184 $timestamp = wfTimestamp( TS_MW
, $timestamp );
185 $modifiedTimes = array(
186 'page' => $timestamp,
187 'user' => $wgUser->getTouched(),
188 'epoch' => $wgCacheEpoch
190 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
192 $maxModified = max( $modifiedTimes );
193 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
195 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
196 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
202 foreach ( $modifiedTimes as $name => $value ) {
203 if ( $info !== '' ) {
206 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
209 # IE sends sizes after the date like this:
210 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
211 # this breaks strtotime().
212 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
214 wfSuppressWarnings(); // E_STRICT system time bitching
215 $clientHeaderTime = strtotime( $clientHeader );
217 if ( !$clientHeaderTime ) {
218 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
221 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
223 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
224 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
225 wfDebug( __METHOD__
. ": effective Last-Modified: " .
226 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
227 if( $clientHeaderTime < $maxModified ) {
228 wfDebug( __METHOD__
. ": STALE, $info\n", false );
233 # Give a 304 response code and disable body output
234 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
235 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
236 $this->sendCacheControl();
239 // Don't output a compressed blob when using ob_gzhandler;
240 // it's technically against HTTP spec and seems to confuse
241 // Firefox when the response gets split over two packets.
242 wfClearOutputBuffers();
247 function setPageTitleActionText( $text ) {
248 $this->mPageTitleActionText
= $text;
251 function getPageTitleActionText () {
252 if ( isset( $this->mPageTitleActionText
) ) {
253 return $this->mPageTitleActionText
;
258 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
260 * @param $policy string The literal string to output as the contents of
261 * the meta tag. Will be parsed according to the spec and output in
265 public function setRobotPolicy( $policy ) {
266 $policy = explode( ',', $policy );
267 $policy = array_map( 'trim', $policy );
269 # The default policy is follow, so if nothing is said explicitly, we
271 if( in_array( 'nofollow', $policy ) ) {
272 $this->mFollowPolicy
= 'nofollow';
274 $this->mFollowPolicy
= 'follow';
277 if( in_array( 'noindex', $policy ) ) {
278 $this->mIndexPolicy
= 'noindex';
280 $this->mIndexPolicy
= 'index';
285 * Set the index policy for the page, but leave the follow policy un-
288 * @param $policy string Either 'index' or 'noindex'.
291 public function setIndexPolicy( $policy ) {
292 $policy = trim( $policy );
293 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
294 $this->mIndexPolicy
= $policy;
299 * Set the follow policy for the page, but leave the index policy un-
302 * @param $policy string Either 'follow' or 'nofollow'.
305 public function setFollowPolicy( $policy ) {
306 $policy = trim( $policy );
307 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
308 $this->mFollowPolicy
= $policy;
312 public function setHTMLTitle( $name ) { $this->mHTMLtitle
= $name; }
313 public function setPageTitle( $name ) {
315 $name = $wgContLang->convert( $name, true );
316 $this->mPagetitle
= $name;
318 $taction = $this->getPageTitleActionText();
319 if( !empty( $taction ) ) {
320 $name .= ' - '.$taction;
323 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
326 public function getHTMLTitle() { return $this->mHTMLtitle
; }
327 public function getPageTitle() { return $this->mPagetitle
; }
328 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
329 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
330 public function getSubtitle() { return $this->mSubtitle
; }
331 public function isArticle() { return $this->mIsarticle
; }
332 public function setPrintable() { $this->mPrintable
= true; }
333 public function isPrintable() { return $this->mPrintable
; }
334 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
335 public function isSyndicated() { return $this->mShowFeedLinks
; }
336 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
337 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
338 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
339 public function getOnloadHandler() { return $this->mOnloadHandler
; }
340 public function disable() { $this->mDoNothing
= true; }
342 public function setArticleRelated( $v ) {
343 $this->mIsArticleRelated
= $v;
345 $this->mIsarticle
= false;
348 public function setArticleFlag( $v ) {
349 $this->mIsarticle
= $v;
351 $this->mIsArticleRelated
= $v;
355 public function isArticleRelated() { return $this->mIsArticleRelated
; }
357 public function getLanguageLinks() { return $this->mLanguageLinks
; }
358 public function addLanguageLinks($newLinkArray) {
359 $this->mLanguageLinks +
= $newLinkArray;
361 public function setLanguageLinks($newLinkArray) {
362 $this->mLanguageLinks
= $newLinkArray;
365 public function getCategoryLinks() {
366 return $this->mCategoryLinks
;
370 * Add an array of categories, with names in the keys
372 public function addCategoryLinks( $categories ) {
373 global $wgUser, $wgContLang;
375 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
379 # Add the links to a LinkBatch
380 $arr = array( NS_CATEGORY
=> $categories );
382 $lb->setArray( $arr );
384 # Fetch existence plus the hiddencat property
385 $dbr = wfGetDB( DB_SLAVE
);
386 $pageTable = $dbr->tableName( 'page' );
387 $where = $lb->constructSet( 'page', $dbr );
388 $propsTable = $dbr->tableName( 'page_props' );
389 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
390 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
391 $res = $dbr->query( $sql, __METHOD__
);
393 # Add the results to the link cache
394 $lb->addResultToCache( LinkCache
::singleton(), $res );
396 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
397 $categories = array_combine( array_keys( $categories ),
398 array_fill( 0, count( $categories ), 'normal' ) );
400 # Mark hidden categories
401 foreach ( $res as $row ) {
402 if ( isset( $row->pp_value
) ) {
403 $categories[$row->page_title
] = 'hidden';
407 # Add the remaining categories to the skin
408 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
409 $sk = $wgUser->getSkin();
410 foreach ( $categories as $category => $type ) {
411 $origcategory = $category;
412 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
413 $wgContLang->findVariantLink( $category, $title, true );
414 if ( $category != $origcategory )
415 if ( array_key_exists( $category, $categories ) )
417 $text = $wgContLang->convertHtml( $title->getText() );
418 $this->mCategoryLinks
[$type][] = $sk->makeLinkObj( $title, $text );
423 public function setCategoryLinks($categories) {
424 $this->mCategoryLinks
= array();
425 $this->addCategoryLinks($categories);
428 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
429 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
431 public function disallowUserJs() { $this->mAllowUserJs
= false; }
432 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
434 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
435 public function addHTML( $text ) { $this->mBodytext
.= $text; }
436 public function clearHTML() { $this->mBodytext
= ''; }
437 public function getHTML() { return $this->mBodytext
; }
438 public function debug( $text ) { $this->mDebugtext
.= $text; }
441 public function setParserOptions( $options ) {
442 wfDeprecated( __METHOD__
);
443 return $this->parserOptions( $options );
446 public function parserOptions( $options = null ) {
447 if ( !$this->mParserOptions
) {
448 $this->mParserOptions
= new ParserOptions
;
450 return wfSetVar( $this->mParserOptions
, $options );
454 * Set the revision ID which will be seen by the wiki text parser
455 * for things such as embedded {{REVISIONID}} variable use.
456 * @param mixed $revid an integer, or NULL
457 * @return mixed previous value
459 public function setRevisionId( $revid ) {
460 $val = is_null( $revid ) ?
null : intval( $revid );
461 return wfSetVar( $this->mRevisionId
, $val );
464 public function getRevisionId() {
465 return $this->mRevisionId
;
469 * Convert wikitext to HTML and add it to the buffer
470 * Default assumes that the current page title will
473 * @param string $text
474 * @param bool $linestart
476 public function addWikiText( $text, $linestart = true ) {
478 $this->addWikiTextTitle($text, $wgTitle, $linestart);
481 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
482 $this->addWikiTextTitle($text, $title, $linestart);
485 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
486 $this->addWikiTextTitle( $text, $title, $linestart, true );
489 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
492 wfProfileIn( __METHOD__
);
494 wfIncrStats( 'pcache_not_possible' );
496 $popts = $this->parserOptions();
497 $oldTidy = $popts->setTidy( $tidy );
499 $parserOutput = $wgParser->parse( $text, $title, $popts,
500 $linestart, true, $this->mRevisionId
);
502 $popts->setTidy( $oldTidy );
504 $this->addParserOutput( $parserOutput );
506 wfProfileOut( __METHOD__
);
511 * @param ParserOutput object &$parserOutput
513 public function addParserOutputNoText( &$parserOutput ) {
514 global $wgTitle, $wgExemptFromUserRobotsControl, $wgContentNamespaces;
516 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
517 $this->addCategoryLinks( $parserOutput->getCategories() );
518 $this->mNewSectionLink
= $parserOutput->getNewSection();
520 if( is_null( $wgExemptFromUserRobotsControl ) ) {
521 $bannedNamespaces = $wgContentNamespaces;
523 $bannedNamespaces = $wgExemptFromUserRobotsControl;
525 if( !in_array( $wgTitle->getNamespace(), $bannedNamespaces ) ) {
526 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
528 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
531 $this->addKeywords( $parserOutput );
532 $this->mParseWarnings
= $parserOutput->getWarnings();
533 if ( $parserOutput->getCacheTime() == -1 ) {
534 $this->enableClientCache( false );
536 $this->mNoGallery
= $parserOutput->getNoGallery();
537 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
539 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
540 if ( isset( $this->mTemplateIds
[$ns] ) ) {
541 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
543 $this->mTemplateIds
[$ns] = $dbks;
547 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
548 $this->setPageTitle( $dt );
549 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
550 $this->setPageTitle( $title );
552 // Hooks registered in the object
553 global $wgParserOutputHooks;
554 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
555 list( $hookName, $data ) = $hookInfo;
556 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
557 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
561 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
566 * @param ParserOutput &$parserOutput
568 function addParserOutput( &$parserOutput ) {
569 $this->addParserOutputNoText( $parserOutput );
570 $text = $parserOutput->getText();
571 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
572 $this->addHTML( $text );
576 * Add wikitext to the buffer, assuming that this is the primary text for a page view
577 * Saves the text into the parser cache if possible.
579 * @param string $text
580 * @param Article $article
582 * @deprecated Use Article::outputWikitext
584 public function addPrimaryWikiText( $text, $article, $cache = true ) {
585 global $wgParser, $wgUser;
587 wfDeprecated( __METHOD__
);
589 $popts = $this->parserOptions();
590 $popts->setTidy(true);
591 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
592 $popts, true, true, $this->mRevisionId
);
593 $popts->setTidy(false);
594 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
595 $parserCache = ParserCache
::singleton();
596 $parserCache->save( $parserOutput, $article, $wgUser );
599 $this->addParserOutput( $parserOutput );
603 * @deprecated use addWikiTextTidy()
605 public function addSecondaryWikiText( $text, $linestart = true ) {
607 wfDeprecated( __METHOD__
);
608 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
612 * Add wikitext with tidy enabled
614 public function addWikiTextTidy( $text, $linestart = true ) {
616 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
621 * Add the output of a QuickTemplate to the output buffer
623 * @param QuickTemplate $template
625 public function addTemplate( &$template ) {
627 $template->execute();
628 $this->addHTML( ob_get_contents() );
633 * Parse wikitext and return the HTML.
635 * @param string $text
636 * @param bool $linestart Is this the start of a line?
637 * @param bool $interface ??
639 public function parse( $text, $linestart = true, $interface = false ) {
640 global $wgParser, $wgTitle;
641 if( is_null( $wgTitle ) ) {
642 throw new MWException( 'Empty $wgTitle in ' . __METHOD__
);
644 $popts = $this->parserOptions();
645 if ( $interface) { $popts->setInterfaceMessage(true); }
646 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
647 $linestart, true, $this->mRevisionId
);
648 if ( $interface) { $popts->setInterfaceMessage(false); }
649 return $parserOutput->getText();
652 /** Parse wikitext, strip paragraphs, and return the HTML. */
653 public function parseInline( $text, $linestart = true, $interface = false ) {
654 $parsed = $this->parse( $text, $linestart, $interface );
657 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
665 * @param Article $article
668 * @return bool True if successful, else false.
670 public function tryParserCache( &$article, $user ) {
671 $parserCache = ParserCache
::singleton();
672 $parserOutput = $parserCache->get( $article, $user );
673 if ( $parserOutput !== false ) {
674 $this->addParserOutput( $parserOutput );
682 * @param int $maxage Maximum cache time on the Squid, in seconds.
684 public function setSquidMaxage( $maxage ) {
685 $this->mSquidMaxage
= $maxage;
689 * Use enableClientCache(false) to force it to send nocache headers
692 public function enableClientCache( $state ) {
693 return wfSetVar( $this->mEnableClientCache
, $state );
696 function getCacheVaryCookies() {
697 global $wgCookiePrefix, $wgCacheVaryCookies;
699 if ( $cookies === null ) {
700 $cookies = array_merge(
702 "{$wgCookiePrefix}Token",
703 "{$wgCookiePrefix}LoggedOut",
708 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
713 function uncacheableBecauseRequestVars() {
715 return $wgRequest->getText('useskin', false) === false
716 && $wgRequest->getText('uselang', false) === false;
720 * Check if the request has a cache-varying cookie header
721 * If it does, it's very important that we don't allow public caching
723 function haveCacheVaryCookies() {
725 $cookieHeader = $wgRequest->getHeader( 'cookie' );
726 if ( $cookieHeader === false ) {
729 $cvCookies = $this->getCacheVaryCookies();
730 foreach ( $cvCookies as $cookieName ) {
731 # Check for a simple string match, like the way squid does it
732 if ( strpos( $cookieHeader, $cookieName ) ) {
733 wfDebug( __METHOD__
.": found $cookieName\n" );
737 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
741 /** Get a complete X-Vary-Options header */
742 public function getXVO() {
743 $cvCookies = $this->getCacheVaryCookies();
744 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
746 foreach ( $cvCookies as $cookieName ) {
752 $xvo .= 'string-contains=' . $cookieName;
757 public function sendCacheControl() {
758 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
760 $response = $wgRequest->response();
761 if ($wgUseETag && $this->mETag
)
762 $response->header("ETag: $this->mETag");
764 # don't serve compressed data to clients who can't handle it
765 # maintain different caches for logged-in users and non-logged in ones
766 $response->header( 'Vary: Accept-Encoding, Cookie' );
768 # Add an X-Vary-Options header for Squid with Wikimedia patches
769 $response->header( $this->getXVO() );
771 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
772 if( $wgUseSquid && session_id() == '' &&
773 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
776 # We'll purge the proxy cache explicitly, but require end user agents
777 # to revalidate against the proxy on each visit.
778 # Surrogate-Control controls our Squid, Cache-Control downstream caches
779 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
780 # start with a shorter timeout for initial testing
781 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
782 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
783 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
785 # We'll purge the proxy cache for anons explicitly, but require end user agents
786 # to revalidate against the proxy on each visit.
787 # IMPORTANT! The Squid needs to replace the Cache-Control header with
788 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
789 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
790 # start with a shorter timeout for initial testing
791 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
792 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
795 # We do want clients to cache if they can, but they *must* check for updates
796 # on revisiting the page.
797 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
798 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
799 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
801 if($this->mLastModified
) {
802 $response->header( "Last-Modified: {$this->mLastModified}" );
805 wfDebug( __METHOD__
. ": no caching **\n", false );
807 # In general, the absence of a last modified header should be enough to prevent
808 # the client from using its cache. We send a few other things just to make sure.
809 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
810 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
811 $response->header( 'Pragma: no-cache' );
816 * Finally, all the text has been munged and accumulated into
817 * the object, let's actually output it:
819 public function output() {
820 global $wgUser, $wgOutputEncoding, $wgRequest;
821 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
822 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
823 global $wgEnableMWSuggest, $wgUniversalEditButton;
824 global $wgArticle, $wgTitle;
826 if( $this->mDoNothing
){
830 wfProfileIn( __METHOD__
);
832 if ( '' != $this->mRedirect
) {
833 # Standards require redirect URLs to be absolute
834 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
835 if( $this->mRedirectCode
== '301') {
836 if( !$wgDebugRedirects ) {
837 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
839 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
842 $this->sendCacheControl();
844 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
845 if( $wgDebugRedirects ) {
846 $url = htmlspecialchars( $this->mRedirect
);
847 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
848 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
849 print "</body>\n</html>\n";
851 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
853 wfProfileOut( __METHOD__
);
856 elseif ( $this->mStatusCode
)
858 $statusMessage = array(
860 101 => 'Switching Protocols',
865 203 => 'Non-Authoritative Information',
867 205 => 'Reset Content',
868 206 => 'Partial Content',
869 207 => 'Multi-Status',
870 300 => 'Multiple Choices',
871 301 => 'Moved Permanently',
874 304 => 'Not Modified',
876 307 => 'Temporary Redirect',
877 400 => 'Bad Request',
878 401 => 'Unauthorized',
879 402 => 'Payment Required',
882 405 => 'Method Not Allowed',
883 406 => 'Not Acceptable',
884 407 => 'Proxy Authentication Required',
885 408 => 'Request Timeout',
888 411 => 'Length Required',
889 412 => 'Precondition Failed',
890 413 => 'Request Entity Too Large',
891 414 => 'Request-URI Too Large',
892 415 => 'Unsupported Media Type',
893 416 => 'Request Range Not Satisfiable',
894 417 => 'Expectation Failed',
895 422 => 'Unprocessable Entity',
897 424 => 'Failed Dependency',
898 500 => 'Internal Server Error',
899 501 => 'Not Implemented',
900 502 => 'Bad Gateway',
901 503 => 'Service Unavailable',
902 504 => 'Gateway Timeout',
903 505 => 'HTTP Version Not Supported',
904 507 => 'Insufficient Storage'
907 if ( $statusMessage[$this->mStatusCode
] )
908 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
911 $sk = $wgUser->getSkin();
914 $this->addScriptFile( 'ajax.js' );
916 wfRunHooks( 'AjaxAddScript', array( &$this ) );
918 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
919 $this->addScriptFile( 'ajaxwatch.js' );
922 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
923 $this->addScriptFile( 'mwsuggest.js' );
927 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
928 $this->addScriptFile( 'rightclickedit.js' );
931 if( $wgUniversalEditButton ) {
932 if( isset( $wgArticle ) && isset( $wgTitle ) && $wgTitle->quickUserCan( 'edit' )
933 && ( $wgTitle->exists() ||
$wgTitle->quickUserCan( 'create' ) ) ) {
934 // Original UniversalEditButton
935 $this->addLink( array(
936 'rel' => 'alternate',
937 'type' => 'application/x-wiki',
938 'title' => wfMsg( 'edit' ),
939 'href' => $wgTitle->getFullURL( 'action=edit' )
941 // Alternate edit link
942 $this->addLink( array(
944 'title' => wfMsg( 'edit' ),
945 'href' => $wgTitle->getFullURL( 'action=edit' )
950 # Buffer output; final headers may depend on later processing
953 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
954 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
956 if ($this->mArticleBodyOnly
) {
957 $this->out($this->mBodytext
);
959 // Hook that allows last minute changes to the output page, e.g.
960 // adding of CSS or Javascript by extensions.
961 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
963 wfProfileIn( 'Output-skin' );
964 $sk->outputPage( $this );
965 wfProfileOut( 'Output-skin' );
968 $this->sendCacheControl();
970 wfProfileOut( __METHOD__
);
977 public function out( $ins ) {
978 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
979 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
982 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
983 if ( false === $outs ) { $outs = $ins; }
991 public static function setEncodings() {
992 global $wgInputEncoding, $wgOutputEncoding;
993 global $wgUser, $wgContLang;
995 $wgInputEncoding = strtolower( $wgInputEncoding );
997 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
998 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1001 $wgOutputEncoding = $wgInputEncoding;
1005 * Deprecated, use wfReportTime() instead.
1009 public function reportTime() {
1010 wfDeprecated( __METHOD__
);
1011 $time = wfReportTime();
1016 * Produce a "user is blocked" page.
1018 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1021 function blockedPage( $return = true ) {
1022 global $wgUser, $wgContLang, $wgTitle, $wgLang;
1024 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1025 $this->setRobotPolicy( 'noindex,nofollow' );
1026 $this->setArticleRelated( false );
1028 $name = User
::whoIs( $wgUser->blockedBy() );
1029 $reason = $wgUser->blockedFor();
1030 if( $reason == '' ) {
1031 $reason = wfMsg( 'blockednoreason' );
1033 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1036 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1038 $blockid = $wgUser->mBlock
->mId
;
1040 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1041 if ( $blockExpiry == 'infinity' ) {
1042 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1043 // Search for localization in 'ipboptions'
1044 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1045 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1046 if ( strpos( $option, ":" ) === false )
1048 list( $show, $value ) = explode( ":", $option );
1049 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1050 $blockExpiry = $show;
1055 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1058 if ( $wgUser->mBlock
->mAuto
) {
1059 $msg = 'autoblockedtext';
1061 $msg = 'blockedtext';
1064 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1065 * This could be a username, an ip range, or a single ip. */
1066 $intended = $wgUser->mBlock
->mAddress
;
1068 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1070 # Don't auto-return to special pages
1072 $return = $wgTitle->getNamespace() > -1 ?
$wgTitle : NULL;
1073 $this->returnToMain( null, $return );
1078 * Output a standard error page
1080 * @param string $title Message key for page title
1081 * @param string $msg Message key for page text
1082 * @param array $params Message parameters
1084 public function showErrorPage( $title, $msg, $params = array() ) {
1086 if ( isset($wgTitle) ) {
1087 $this->mDebugtext
.= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
1089 $this->setPageTitle( wfMsg( $title ) );
1090 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1091 $this->setRobotPolicy( 'noindex,nofollow' );
1092 $this->setArticleRelated( false );
1093 $this->enableClientCache( false );
1094 $this->mRedirect
= '';
1095 $this->mBodytext
= '';
1097 array_unshift( $params, 'parse' );
1098 array_unshift( $params, $msg );
1099 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1101 $this->returnToMain();
1105 * Output a standard permission error page
1107 * @param array $errors Error message keys
1109 public function showPermissionsErrorPage( $errors, $action = null )
1113 $this->mDebugtext
.= 'Original title: ' .
1114 $wgTitle->getPrefixedText() . "\n";
1115 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1116 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1117 $this->setRobotPolicy( 'noindex,nofollow' );
1118 $this->setArticleRelated( false );
1119 $this->enableClientCache( false );
1120 $this->mRedirect
= '';
1121 $this->mBodytext
= '';
1122 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1126 public function errorpage( $title, $msg ) {
1127 wfDeprecated( __METHOD__
);
1128 throw new ErrorPageError( $title, $msg );
1132 * Display an error page indicating that a given version of MediaWiki is
1133 * required to use it
1135 * @param mixed $version The version of MediaWiki needed to use the page
1137 public function versionRequired( $version ) {
1138 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1139 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1140 $this->setRobotPolicy( 'noindex,nofollow' );
1141 $this->setArticleRelated( false );
1142 $this->mBodytext
= '';
1144 $this->addWikiMsg( 'versionrequiredtext', $version );
1145 $this->returnToMain();
1149 * Display an error page noting that a given permission bit is required.
1151 * @param string $permission key required
1153 public function permissionRequired( $permission ) {
1156 $this->setPageTitle( wfMsg( 'badaccess' ) );
1157 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1158 $this->setRobotPolicy( 'noindex,nofollow' );
1159 $this->setArticleRelated( false );
1160 $this->mBodytext
= '';
1162 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1163 User
::getGroupsWithPermission( $permission ) );
1165 $this->addWikiMsg( 'badaccess-groups',
1166 implode( ', ', $groups ),
1169 $this->addWikiMsg( 'badaccess-group0' );
1171 $this->returnToMain();
1175 * Use permissionRequired.
1178 public function sysopRequired() {
1179 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1183 * Use permissionRequired.
1186 public function developerRequired() {
1187 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1191 * Produce the stock "please login to use the wiki" page
1193 public function loginToUse() {
1194 global $wgUser, $wgTitle, $wgContLang;
1196 if( $wgUser->isLoggedIn() ) {
1197 $this->permissionRequired( 'read' );
1201 $skin = $wgUser->getSkin();
1203 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1204 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1205 $this->setRobotPolicy( 'noindex,nofollow' );
1206 $this->setArticleFlag( false );
1208 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1209 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1210 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1211 $this->addHTML( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1213 # Don't return to the main page if the user can't read it
1214 # otherwise we'll end up in a pointless loop
1215 $mainPage = Title
::newMainPage();
1216 if( $mainPage->userCanRead() )
1217 $this->returnToMain( null, $mainPage );
1221 public function databaseError( $fname, $sql, $error, $errno ) {
1222 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1226 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1227 * @return string The wikitext error-messages, formatted into a list.
1229 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1230 if ($action == null) {
1231 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1234 $action_desc = wfMsg( "action-$action" );
1235 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1238 if (count( $errors ) > 1) {
1239 $text .= '<ul class="permissions-errors">' . "\n";
1241 foreach( $errors as $error )
1244 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1249 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1256 * Display a page stating that the Wiki is in read-only mode,
1257 * and optionally show the source of the page that the user
1258 * was trying to edit. Should only be called (for this
1259 * purpose) after wfReadOnly() has returned true.
1261 * For historical reasons, this function is _also_ used to
1262 * show the error message when a user tries to edit a page
1263 * they are not allowed to edit. (Unless it's because they're
1264 * blocked, then we show blockedPage() instead.) In this
1265 * case, the second parameter should be set to true and a list
1266 * of reasons supplied as the third parameter.
1268 * @todo Needs to be split into multiple functions.
1270 * @param string $source Source code to show (or null).
1271 * @param bool $protected Is this a permissions error?
1272 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1274 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1275 global $wgUser, $wgTitle;
1276 $skin = $wgUser->getSkin();
1278 $this->setRobotPolicy( 'noindex,nofollow' );
1279 $this->setArticleRelated( false );
1281 // If no reason is given, just supply a default "I can't let you do
1282 // that, Dave" message. Should only occur if called by legacy code.
1283 if ( $protected && empty($reasons) ) {
1284 $reasons[] = array( 'badaccess-group0' );
1287 if ( !empty($reasons) ) {
1288 // Permissions error
1290 $this->setPageTitle( wfMsg( 'viewsource' ) );
1291 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1293 $this->setPageTitle( wfMsg( 'badaccess' ) );
1295 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1297 // Wiki is read only
1298 $this->setPageTitle( wfMsg( 'readonly' ) );
1299 $reason = wfReadOnlyReason();
1300 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1303 // Show source, if supplied
1304 if( is_string( $source ) ) {
1305 $this->addWikiMsg( 'viewsourcetext' );
1306 $text = Xml
::openElement( 'textarea',
1307 array( 'id' => 'wpTextbox1',
1308 'name' => 'wpTextbox1',
1309 'cols' => $wgUser->getOption( 'cols' ),
1310 'rows' => $wgUser->getOption( 'rows' ),
1311 'readonly' => 'readonly' ) );
1312 $text .= htmlspecialchars( $source );
1313 $text .= Xml
::closeElement( 'textarea' );
1314 $this->addHTML( $text );
1316 // Show templates used by this article
1317 $skin = $wgUser->getSkin();
1318 $article = new Article( $wgTitle );
1319 $this->addHTML( "<div class='templatesUsed'>
1320 {$skin->formatTemplates( $article->getUsedTemplates() )}
1325 # If the title doesn't exist, it's fairly pointless to print a return
1326 # link to it. After all, you just tried editing it and couldn't, so
1327 # what's there to do there?
1328 if( $wgTitle->exists() ) {
1329 $this->returnToMain( null, $wgTitle );
1334 public function fatalError( $message ) {
1335 wfDeprecated( __METHOD__
);
1336 throw new FatalError( $message );
1340 public function unexpectedValueError( $name, $val ) {
1341 wfDeprecated( __METHOD__
);
1342 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1346 public function fileCopyError( $old, $new ) {
1347 wfDeprecated( __METHOD__
);
1348 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1352 public function fileRenameError( $old, $new ) {
1353 wfDeprecated( __METHOD__
);
1354 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1358 public function fileDeleteError( $name ) {
1359 wfDeprecated( __METHOD__
);
1360 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1364 public function fileNotFoundError( $name ) {
1365 wfDeprecated( __METHOD__
);
1366 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1369 public function showFatalError( $message ) {
1370 $this->setPageTitle( wfMsg( "internalerror" ) );
1371 $this->setRobotPolicy( "noindex,nofollow" );
1372 $this->setArticleRelated( false );
1373 $this->enableClientCache( false );
1374 $this->mRedirect
= '';
1375 $this->mBodytext
= $message;
1378 public function showUnexpectedValueError( $name, $val ) {
1379 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1382 public function showFileCopyError( $old, $new ) {
1383 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1386 public function showFileRenameError( $old, $new ) {
1387 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1390 public function showFileDeleteError( $name ) {
1391 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1394 public function showFileNotFoundError( $name ) {
1395 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1399 * Add a "return to" link pointing to a specified title
1401 * @param Title $title Title to link
1403 public function addReturnTo( $title ) {
1405 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1406 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1407 $this->addHTML( "<p>{$link}</p>\n" );
1411 * Add a "return to" link pointing to a specified title,
1412 * or the title indicated in the request, or else the main page
1414 * @param null $unused No longer used
1415 * @param Title $returnto Title to return to
1417 public function returnToMain( $unused = null, $returnto = NULL ) {
1420 if ( $returnto == NULL ) {
1421 $returnto = $wgRequest->getText( 'returnto' );
1424 if ( '' === $returnto ) {
1425 $returnto = Title
::newMainPage();
1428 if ( is_object( $returnto ) ) {
1429 $titleObj = $returnto;
1431 $titleObj = Title
::newFromText( $returnto );
1433 if ( !is_object( $titleObj ) ) {
1434 $titleObj = Title
::newMainPage();
1437 $this->addReturnTo( $titleObj );
1441 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1442 * and uses the first 10 of them for META keywords
1444 * @param ParserOutput &$parserOutput
1446 private function addKeywords( &$parserOutput ) {
1448 $this->addKeyword( $wgTitle->getPrefixedText() );
1450 $links2d =& $parserOutput->getLinks();
1451 if ( !is_array( $links2d ) ) {
1454 foreach ( $links2d as $dbkeys ) {
1455 foreach( $dbkeys as $dbkey => $unused ) {
1456 $this->addKeyword( $dbkey );
1457 if ( ++
$count > 10 ) {
1465 * @return string The doctype, opening <html>, and head element.
1467 public function headElement( Skin
$sk ) {
1468 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1469 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1470 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1472 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1473 $this->addStyle( 'common/wikiprintable.css', 'print' );
1474 $sk->setupUserCss( $this );
1478 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1479 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1482 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1484 if ( '' == $this->getHTMLTitle() ) {
1485 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1488 $rtl = $wgContLang->isRTL() ?
" dir='RTL'" : '';
1489 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1490 foreach($wgXhtmlNamespaces as $tag => $ns) {
1491 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1493 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1494 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t\t";
1495 $ret .= implode( "\t\t", array(
1496 $this->getHeadLinks(),
1497 $this->buildCssLinks(),
1498 $sk->getHeadScripts( $this->mAllowUserJs
),
1500 $this->getHeadItems(),
1503 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1506 if ($wgUseTrackbacks && $this->isArticleRelated())
1507 $ret .= $wgTitle->trackbackRDF();
1509 $ret .= "</head>\n";
1513 protected function addDefaultMeta() {
1515 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1516 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1518 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1519 if( $p !== 'index,follow' ) {
1520 // http://www.robotstxt.org/wc/meta-user.html
1521 // Only show if it's different from the default robots policy
1522 $this->addMeta( 'robots', $p );
1525 if ( count( $this->mKeywords
) > 0 ) {
1530 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1535 * @return string HTML tag links to be put in the header.
1537 public function getHeadLinks() {
1538 global $wgRequest, $wgFeed;
1540 // Ideally this should happen earlier, somewhere. :P
1541 $this->addDefaultMeta();
1545 foreach ( $this->mMetatags
as $tag ) {
1546 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1548 $tag[0] = substr( $tag[0], 5 );
1552 $tags[] = Xml
::element( 'meta',
1555 'content' => $tag[1] ) );
1557 foreach ( $this->mLinktags
as $tag ) {
1558 $tags[] = Xml
::element( 'link', $tag );
1563 foreach( $this->getSyndicationLinks() as $format => $link ) {
1564 # Use the page name for the title (accessed through $wgTitle since
1565 # there's no other way). In principle, this could lead to issues
1566 # with having the same name for different feeds corresponding to
1567 # the same page, but we can't avoid that at this low a level.
1569 $tags[] = $this->feedLink(
1572 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1575 # Recent changes feed should appear on every page (except recentchanges,
1576 # that would be redundant). Put it after the per-page feed to avoid
1577 # changing existing behavior. It's still available, probably via a
1578 # menu in your browser. Some sites might have a different feed they'd
1579 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1580 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1581 # If so, use it instead.
1583 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1584 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1586 if ( $wgOverrideSiteFeed ) {
1587 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1588 $tags[] = $this->feedLink (
1590 htmlspecialchars( $feedUrl ),
1591 wfMsg( "site-{$type}-feed", $wgSitename ) );
1594 else if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1595 foreach( $wgFeedClasses as $format => $class ) {
1596 $tags[] = $this->feedLink(
1598 $rctitle->getFullURL( "feed={$format}" ),
1599 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1604 return implode( "\n\t\t", $tags ) . "\n";
1608 * Return URLs for each supported syndication format for this page.
1609 * @return array associating format keys with URLs
1611 public function getSyndicationLinks() {
1612 global $wgTitle, $wgFeedClasses;
1615 if( $this->isSyndicated() ) {
1616 if( is_string( $this->getFeedAppendQuery() ) ) {
1617 $appendQuery = "&" . $this->getFeedAppendQuery();
1622 foreach( $wgFeedClasses as $format => $class ) {
1623 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1630 * Generate a <link rel/> for an RSS feed.
1632 private function feedLink( $type, $url, $text ) {
1633 return Xml
::element( 'link', array(
1634 'rel' => 'alternate',
1635 'type' => "application/$type+xml",
1641 * Add a local or specified stylesheet, with the given media options.
1642 * Meant primarily for internal use...
1644 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1645 * @param $conditional -- for IE conditional comments, specifying an IE version
1646 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1648 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1651 $options['media'] = $media;
1653 $options['condition'] = $condition;
1655 $options['dir'] = $dir;
1656 $this->styles
[$style] = $options;
1660 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1661 * These will be applied to various media & IE conditionals.
1663 public function buildCssLinks() {
1665 foreach( $this->styles
as $file => $options ) {
1666 $link = $this->styleLink( $file, $options );
1671 return implode( "\n\t\t", $links );
1674 protected function styleLink( $style, $options ) {
1677 if( isset( $options['dir'] ) ) {
1679 $siteDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1680 if( $siteDir != $options['dir'] )
1684 if( isset( $options['media'] ) ) {
1685 $media = $this->transformCssMedia( $options['media'] );
1686 if( is_null( $media ) ) {
1693 if( substr( $style, 0, 1 ) == '/' ||
1694 substr( $style, 0, 5 ) == 'http:' ||
1695 substr( $style, 0, 6 ) == 'https:' ) {
1698 global $wgStylePath, $wgStyleVersion;
1699 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1703 'rel' => 'stylesheet',
1705 'type' => 'text/css' );
1707 $attribs['media'] = $media;
1710 $link = Xml
::element( 'link', $attribs );
1712 if( isset( $options['condition'] ) ) {
1713 $condition = htmlspecialchars( $options['condition'] );
1714 $link = "<!--[if $condition]>$link<![endif]-->";
1719 function transformCssMedia( $media ) {
1720 global $wgRequest, $wgHandheldForIPhone;
1722 // Switch in on-screen display for media testing
1724 'printable' => 'print',
1725 'handheld' => 'handheld',
1727 foreach( $switches as $switch => $targetMedia ) {
1728 if( $wgRequest->getBool( $switch ) ) {
1729 if( $media == $targetMedia ) {
1731 } elseif( $media == 'screen' ) {
1737 // Expand longer media queries as iPhone doesn't grok 'handheld'
1738 if( $wgHandheldForIPhone ) {
1739 $mediaAliases = array(
1740 'screen' => 'screen and (min-device-width: 481px)',
1741 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1744 if( isset( $mediaAliases[$media] ) ) {
1745 $media = $mediaAliases[$media];
1753 * Turn off regular page output and return an error reponse
1754 * for when rate limiting has triggered.
1756 public function rateLimited() {
1759 $this->setPageTitle(wfMsg('actionthrottled'));
1760 $this->setRobotPolicy( 'noindex,follow' );
1761 $this->setArticleRelated( false );
1762 $this->enableClientCache( false );
1763 $this->mRedirect
= '';
1765 $this->setStatusCode(503);
1766 $this->addWikiMsg( 'actionthrottledtext' );
1768 $this->returnToMain( null, $wgTitle );
1772 * Show an "add new section" link?
1776 public function showNewSectionLink() {
1777 return $this->mNewSectionLink
;
1781 * Show a warning about slave lag
1783 * If the lag is higher than $wgSlaveLagCritical seconds,
1784 * then the warning is a bit more obvious. If the lag is
1785 * lower than $wgSlaveLagWarning, then no warning is shown.
1787 * @param int $lag Slave lag
1789 public function showLagWarning( $lag ) {
1790 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1791 if( $lag >= $wgSlaveLagWarning ) {
1792 $message = $lag < $wgSlaveLagCritical
1795 $warning = wfMsgExt( $message, 'parse', $lag );
1796 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1801 * Add a wikitext-formatted message to the output.
1802 * This is equivalent to:
1804 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1806 public function addWikiMsg( /*...*/ ) {
1807 $args = func_get_args();
1808 $name = array_shift( $args );
1809 $this->addWikiMsgArray( $name, $args );
1813 * Add a wikitext-formatted message to the output.
1814 * Like addWikiMsg() except the parameters are taken as an array
1815 * instead of a variable argument list.
1817 * $options is passed through to wfMsgExt(), see that function for details.
1819 public function addWikiMsgArray( $name, $args, $options = array() ) {
1820 $options[] = 'parse';
1821 $text = wfMsgExt( $name, $options, $args );
1822 $this->addHTML( $text );
1826 * This function takes a number of message/argument specifications, wraps them in
1827 * some overall structure, and then parses the result and adds it to the output.
1829 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1830 * on. The subsequent arguments may either be strings, in which case they are the
1831 * message names, or an arrays, in which case the first element is the message name,
1832 * and subsequent elements are the parameters to that message.
1834 * The special named parameter 'options' in a message specification array is passed
1835 * through to the $options parameter of wfMsgExt().
1837 * Don't use this for messages that are not in users interface language.
1841 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1845 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1847 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1848 $msgSpecs = func_get_args();
1849 array_shift( $msgSpecs );
1850 $msgSpecs = array_values( $msgSpecs );
1852 foreach ( $msgSpecs as $n => $spec ) {
1854 if ( is_array( $spec ) ) {
1856 $name = array_shift( $args );
1857 if ( isset( $args['options'] ) ) {
1858 $options = $args['options'];
1859 unset( $args['options'] );
1865 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
1867 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );