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 ) {
314 global $action, $wgContLang;
315 $name = $wgContLang->convert($name, true);
316 $this->mPagetitle
= $name;
317 if(!empty($action)) {
318 $taction = $this->getPageTitleActionText();
319 if( !empty( $taction ) ) {
320 $name .= ' - '.$taction;
324 $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 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
412 $wgContLang->findVariantLink( $category, $title );
413 $text = $wgContLang->convertHtml( $title->getText() );
414 $this->mCategoryLinks
[$type][] = $sk->makeLinkObj( $title, $text );
419 public function setCategoryLinks($categories) {
420 $this->mCategoryLinks
= array();
421 $this->addCategoryLinks($categories);
424 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
425 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
427 public function disallowUserJs() { $this->mAllowUserJs
= false; }
428 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
430 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
431 public function addHTML( $text ) { $this->mBodytext
.= $text; }
432 public function clearHTML() { $this->mBodytext
= ''; }
433 public function getHTML() { return $this->mBodytext
; }
434 public function debug( $text ) { $this->mDebugtext
.= $text; }
437 public function setParserOptions( $options ) {
438 wfDeprecated( __METHOD__
);
439 return $this->parserOptions( $options );
442 public function parserOptions( $options = null ) {
443 if ( !$this->mParserOptions
) {
444 $this->mParserOptions
= new ParserOptions
;
446 return wfSetVar( $this->mParserOptions
, $options );
450 * Set the revision ID which will be seen by the wiki text parser
451 * for things such as embedded {{REVISIONID}} variable use.
452 * @param mixed $revid an integer, or NULL
453 * @return mixed previous value
455 public function setRevisionId( $revid ) {
456 $val = is_null( $revid ) ?
null : intval( $revid );
457 return wfSetVar( $this->mRevisionId
, $val );
460 public function getRevisionId() {
461 return $this->mRevisionId
;
465 * Convert wikitext to HTML and add it to the buffer
466 * Default assumes that the current page title will
469 * @param string $text
470 * @param bool $linestart
472 public function addWikiText( $text, $linestart = true ) {
474 $this->addWikiTextTitle($text, $wgTitle, $linestart);
477 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
478 $this->addWikiTextTitle($text, $title, $linestart);
481 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
482 $this->addWikiTextTitle( $text, $title, $linestart, true );
485 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
488 wfProfileIn( __METHOD__
);
490 wfIncrStats( 'pcache_not_possible' );
492 $popts = $this->parserOptions();
493 $oldTidy = $popts->setTidy( $tidy );
495 $parserOutput = $wgParser->parse( $text, $title, $popts,
496 $linestart, true, $this->mRevisionId
);
498 $popts->setTidy( $oldTidy );
500 $this->addParserOutput( $parserOutput );
502 wfProfileOut( __METHOD__
);
507 * @param ParserOutput object &$parserOutput
509 public function addParserOutputNoText( &$parserOutput ) {
510 global $wgTitle, $wgExemptFromUserRobotsControl, $wgContentNamespaces;
512 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
513 $this->addCategoryLinks( $parserOutput->getCategories() );
514 $this->mNewSectionLink
= $parserOutput->getNewSection();
516 if( is_null( $wgExemptFromUserRobotsControl ) ) {
517 $bannedNamespaces = $wgContentNamespaces;
519 $bannedNamespaces = $wgExemptFromUserRobotsControl;
521 if( !in_array( $wgTitle->getNamespace(), $bannedNamespaces ) ) {
522 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
524 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
527 $this->addKeywords( $parserOutput );
528 $this->mParseWarnings
= $parserOutput->getWarnings();
529 if ( $parserOutput->getCacheTime() == -1 ) {
530 $this->enableClientCache( false );
532 $this->mNoGallery
= $parserOutput->getNoGallery();
533 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
535 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
536 if ( isset( $this->mTemplateIds
[$ns] ) ) {
537 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
539 $this->mTemplateIds
[$ns] = $dbks;
543 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
544 $this->setPageTitle( $dt );
545 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
546 $this->setPageTitle( $title );
548 // Hooks registered in the object
549 global $wgParserOutputHooks;
550 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
551 list( $hookName, $data ) = $hookInfo;
552 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
553 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
557 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
562 * @param ParserOutput &$parserOutput
564 function addParserOutput( &$parserOutput ) {
565 $this->addParserOutputNoText( $parserOutput );
566 $text = $parserOutput->getText();
567 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
568 $this->addHTML( $text );
572 * Add wikitext to the buffer, assuming that this is the primary text for a page view
573 * Saves the text into the parser cache if possible.
575 * @param string $text
576 * @param Article $article
578 * @deprecated Use Article::outputWikitext
580 public function addPrimaryWikiText( $text, $article, $cache = true ) {
581 global $wgParser, $wgUser;
583 wfDeprecated( __METHOD__
);
585 $popts = $this->parserOptions();
586 $popts->setTidy(true);
587 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
588 $popts, true, true, $this->mRevisionId
);
589 $popts->setTidy(false);
590 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
591 $parserCache = ParserCache
::singleton();
592 $parserCache->save( $parserOutput, $article, $wgUser );
595 $this->addParserOutput( $parserOutput );
599 * @deprecated use addWikiTextTidy()
601 public function addSecondaryWikiText( $text, $linestart = true ) {
603 wfDeprecated( __METHOD__
);
604 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
608 * Add wikitext with tidy enabled
610 public function addWikiTextTidy( $text, $linestart = true ) {
612 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
617 * Add the output of a QuickTemplate to the output buffer
619 * @param QuickTemplate $template
621 public function addTemplate( &$template ) {
623 $template->execute();
624 $this->addHTML( ob_get_contents() );
629 * Parse wikitext and return the HTML.
631 * @param string $text
632 * @param bool $linestart Is this the start of a line?
633 * @param bool $interface ??
635 public function parse( $text, $linestart = true, $interface = false ) {
636 global $wgParser, $wgTitle;
637 if( is_null( $wgTitle ) ) {
638 throw new MWException( 'Empty $wgTitle in ' . __METHOD__
);
640 $popts = $this->parserOptions();
641 if ( $interface) { $popts->setInterfaceMessage(true); }
642 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
643 $linestart, true, $this->mRevisionId
);
644 if ( $interface) { $popts->setInterfaceMessage(false); }
645 return $parserOutput->getText();
648 /** Parse wikitext, strip paragraphs, and return the HTML. */
649 public function parseInline( $text, $linestart = true, $interface = false ) {
650 $parsed = $this->parse( $text, $linestart, $interface );
653 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
661 * @param Article $article
664 * @return bool True if successful, else false.
666 public function tryParserCache( &$article, $user ) {
667 $parserCache = ParserCache
::singleton();
668 $parserOutput = $parserCache->get( $article, $user );
669 if ( $parserOutput !== false ) {
670 $this->addParserOutput( $parserOutput );
678 * @param int $maxage Maximum cache time on the Squid, in seconds.
680 public function setSquidMaxage( $maxage ) {
681 $this->mSquidMaxage
= $maxage;
685 * Use enableClientCache(false) to force it to send nocache headers
688 public function enableClientCache( $state ) {
689 return wfSetVar( $this->mEnableClientCache
, $state );
692 function getCacheVaryCookies() {
693 global $wgCookiePrefix, $wgCacheVaryCookies;
695 if ( $cookies === null ) {
696 $cookies = array_merge(
698 "{$wgCookiePrefix}Token",
699 "{$wgCookiePrefix}LoggedOut",
704 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
709 function uncacheableBecauseRequestVars() {
711 return $wgRequest->getText('useskin', false) === false
712 && $wgRequest->getText('uselang', false) === false;
716 * Check if the request has a cache-varying cookie header
717 * If it does, it's very important that we don't allow public caching
719 function haveCacheVaryCookies() {
721 $cookieHeader = $wgRequest->getHeader( 'cookie' );
722 if ( $cookieHeader === false ) {
725 $cvCookies = $this->getCacheVaryCookies();
726 foreach ( $cvCookies as $cookieName ) {
727 # Check for a simple string match, like the way squid does it
728 if ( strpos( $cookieHeader, $cookieName ) ) {
729 wfDebug( __METHOD__
.": found $cookieName\n" );
733 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
737 /** Get a complete X-Vary-Options header */
738 public function getXVO() {
739 $cvCookies = $this->getCacheVaryCookies();
740 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
742 foreach ( $cvCookies as $cookieName ) {
748 $xvo .= 'string-contains=' . $cookieName;
753 public function sendCacheControl() {
754 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
756 $response = $wgRequest->response();
757 if ($wgUseETag && $this->mETag
)
758 $response->header("ETag: $this->mETag");
760 # don't serve compressed data to clients who can't handle it
761 # maintain different caches for logged-in users and non-logged in ones
762 $response->header( 'Vary: Accept-Encoding, Cookie' );
764 # Add an X-Vary-Options header for Squid with Wikimedia patches
765 $response->header( $this->getXVO() );
767 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
768 if( $wgUseSquid && session_id() == '' &&
769 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
772 # We'll purge the proxy cache explicitly, but require end user agents
773 # to revalidate against the proxy on each visit.
774 # Surrogate-Control controls our Squid, Cache-Control downstream caches
775 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
776 # start with a shorter timeout for initial testing
777 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
778 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
779 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
781 # We'll purge the proxy cache for anons explicitly, but require end user agents
782 # to revalidate against the proxy on each visit.
783 # IMPORTANT! The Squid needs to replace the Cache-Control header with
784 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
785 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
786 # start with a shorter timeout for initial testing
787 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
788 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
791 # We do want clients to cache if they can, but they *must* check for updates
792 # on revisiting the page.
793 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
794 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
795 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
797 if($this->mLastModified
) {
798 $response->header( "Last-Modified: {$this->mLastModified}" );
801 wfDebug( __METHOD__
. ": no caching **\n", false );
803 # In general, the absence of a last modified header should be enough to prevent
804 # the client from using its cache. We send a few other things just to make sure.
805 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
806 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
807 $response->header( 'Pragma: no-cache' );
812 * Finally, all the text has been munged and accumulated into
813 * the object, let's actually output it:
815 public function output() {
816 global $wgUser, $wgOutputEncoding, $wgRequest;
817 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
818 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
819 global $wgEnableMWSuggest, $wgUniversalEditButton;
820 global $wgArticle, $wgTitle;
822 if( $this->mDoNothing
){
826 wfProfileIn( __METHOD__
);
828 if ( '' != $this->mRedirect
) {
829 # Standards require redirect URLs to be absolute
830 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
831 if( $this->mRedirectCode
== '301') {
832 if( !$wgDebugRedirects ) {
833 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
835 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
838 $this->sendCacheControl();
840 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
841 if( $wgDebugRedirects ) {
842 $url = htmlspecialchars( $this->mRedirect
);
843 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
844 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
845 print "</body>\n</html>\n";
847 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
849 wfProfileOut( __METHOD__
);
852 elseif ( $this->mStatusCode
)
854 $statusMessage = array(
856 101 => 'Switching Protocols',
861 203 => 'Non-Authoritative Information',
863 205 => 'Reset Content',
864 206 => 'Partial Content',
865 207 => 'Multi-Status',
866 300 => 'Multiple Choices',
867 301 => 'Moved Permanently',
870 304 => 'Not Modified',
872 307 => 'Temporary Redirect',
873 400 => 'Bad Request',
874 401 => 'Unauthorized',
875 402 => 'Payment Required',
878 405 => 'Method Not Allowed',
879 406 => 'Not Acceptable',
880 407 => 'Proxy Authentication Required',
881 408 => 'Request Timeout',
884 411 => 'Length Required',
885 412 => 'Precondition Failed',
886 413 => 'Request Entity Too Large',
887 414 => 'Request-URI Too Large',
888 415 => 'Unsupported Media Type',
889 416 => 'Request Range Not Satisfiable',
890 417 => 'Expectation Failed',
891 422 => 'Unprocessable Entity',
893 424 => 'Failed Dependency',
894 500 => 'Internal Server Error',
895 501 => 'Not Implemented',
896 502 => 'Bad Gateway',
897 503 => 'Service Unavailable',
898 504 => 'Gateway Timeout',
899 505 => 'HTTP Version Not Supported',
900 507 => 'Insufficient Storage'
903 if ( $statusMessage[$this->mStatusCode
] )
904 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
907 $sk = $wgUser->getSkin();
910 $this->addScriptFile( 'ajax.js' );
912 wfRunHooks( 'AjaxAddScript', array( &$this ) );
914 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
915 $this->addScriptFile( 'ajaxwatch.js' );
918 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
919 $this->addScriptFile( 'mwsuggest.js' );
923 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
924 $this->addScriptFile( 'rightclickedit.js' );
927 if( $wgUniversalEditButton ) {
928 if( isset( $wgArticle ) && isset( $wgTitle ) && $wgTitle->quickUserCan( 'edit' )
929 && ( $wgTitle->exists() ||
$wgTitle->quickUserCan( 'create' ) ) ) {
930 // Original UniversalEditButton
931 $this->addLink( array(
932 'rel' => 'alternate',
933 'type' => 'application/x-wiki',
934 'title' => wfMsg( 'edit' ),
935 'href' => $wgTitle->getFullURL( 'action=edit' )
937 // Alternate edit link
938 $this->addLink( array(
940 'title' => wfMsg( 'edit' ),
941 'href' => $wgTitle->getFullURL( 'action=edit' )
946 # Buffer output; final headers may depend on later processing
949 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
950 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
952 if ($this->mArticleBodyOnly
) {
953 $this->out($this->mBodytext
);
955 // Hook that allows last minute changes to the output page, e.g.
956 // adding of CSS or Javascript by extensions.
957 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
959 wfProfileIn( 'Output-skin' );
960 $sk->outputPage( $this );
961 wfProfileOut( 'Output-skin' );
964 $this->sendCacheControl();
966 wfProfileOut( __METHOD__
);
973 public function out( $ins ) {
974 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
975 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
978 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
979 if ( false === $outs ) { $outs = $ins; }
987 public static function setEncodings() {
988 global $wgInputEncoding, $wgOutputEncoding;
989 global $wgUser, $wgContLang;
991 $wgInputEncoding = strtolower( $wgInputEncoding );
993 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
994 $wgOutputEncoding = strtolower( $wgOutputEncoding );
997 $wgOutputEncoding = $wgInputEncoding;
1001 * Deprecated, use wfReportTime() instead.
1005 public function reportTime() {
1006 wfDeprecated( __METHOD__
);
1007 $time = wfReportTime();
1012 * Produce a "user is blocked" page.
1014 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1017 function blockedPage( $return = true ) {
1018 global $wgUser, $wgContLang, $wgTitle, $wgLang;
1020 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1021 $this->setRobotPolicy( 'noindex,nofollow' );
1022 $this->setArticleRelated( false );
1024 $name = User
::whoIs( $wgUser->blockedBy() );
1025 $reason = $wgUser->blockedFor();
1026 if( $reason == '' ) {
1027 $reason = wfMsg( 'blockednoreason' );
1029 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1032 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1034 $blockid = $wgUser->mBlock
->mId
;
1036 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1037 if ( $blockExpiry == 'infinity' ) {
1038 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1039 // Search for localization in 'ipboptions'
1040 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1041 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1042 if ( strpos( $option, ":" ) === false )
1044 list( $show, $value ) = explode( ":", $option );
1045 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1046 $blockExpiry = $show;
1051 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1054 if ( $wgUser->mBlock
->mAuto
) {
1055 $msg = 'autoblockedtext';
1057 $msg = 'blockedtext';
1060 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1061 * This could be a username, an ip range, or a single ip. */
1062 $intended = $wgUser->mBlock
->mAddress
;
1064 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1066 # Don't auto-return to special pages
1068 $return = $wgTitle->getNamespace() > -1 ?
$wgTitle : NULL;
1069 $this->returnToMain( null, $return );
1074 * Output a standard error page
1076 * @param string $title Message key for page title
1077 * @param string $msg Message key for page text
1078 * @param array $params Message parameters
1080 public function showErrorPage( $title, $msg, $params = array() ) {
1082 if ( isset($wgTitle) ) {
1083 $this->mDebugtext
.= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
1085 $this->setPageTitle( wfMsg( $title ) );
1086 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1087 $this->setRobotPolicy( 'noindex,nofollow' );
1088 $this->setArticleRelated( false );
1089 $this->enableClientCache( false );
1090 $this->mRedirect
= '';
1091 $this->mBodytext
= '';
1093 array_unshift( $params, 'parse' );
1094 array_unshift( $params, $msg );
1095 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1097 $this->returnToMain();
1101 * Output a standard permission error page
1103 * @param array $errors Error message keys
1105 public function showPermissionsErrorPage( $errors, $action = null )
1109 $this->mDebugtext
.= 'Original title: ' .
1110 $wgTitle->getPrefixedText() . "\n";
1111 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1112 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1113 $this->setRobotPolicy( 'noindex,nofollow' );
1114 $this->setArticleRelated( false );
1115 $this->enableClientCache( false );
1116 $this->mRedirect
= '';
1117 $this->mBodytext
= '';
1118 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1122 public function errorpage( $title, $msg ) {
1123 wfDeprecated( __METHOD__
);
1124 throw new ErrorPageError( $title, $msg );
1128 * Display an error page indicating that a given version of MediaWiki is
1129 * required to use it
1131 * @param mixed $version The version of MediaWiki needed to use the page
1133 public function versionRequired( $version ) {
1134 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1135 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1136 $this->setRobotPolicy( 'noindex,nofollow' );
1137 $this->setArticleRelated( false );
1138 $this->mBodytext
= '';
1140 $this->addWikiMsg( 'versionrequiredtext', $version );
1141 $this->returnToMain();
1145 * Display an error page noting that a given permission bit is required.
1147 * @param string $permission key required
1149 public function permissionRequired( $permission ) {
1152 $this->setPageTitle( wfMsg( 'badaccess' ) );
1153 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1154 $this->setRobotPolicy( 'noindex,nofollow' );
1155 $this->setArticleRelated( false );
1156 $this->mBodytext
= '';
1158 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1159 User
::getGroupsWithPermission( $permission ) );
1161 $this->addWikiMsg( 'badaccess-groups',
1162 implode( ', ', $groups ),
1165 $this->addWikiMsg( 'badaccess-group0' );
1167 $this->returnToMain();
1171 * Use permissionRequired.
1174 public function sysopRequired() {
1175 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1179 * Use permissionRequired.
1182 public function developerRequired() {
1183 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1187 * Produce the stock "please login to use the wiki" page
1189 public function loginToUse() {
1190 global $wgUser, $wgTitle, $wgContLang;
1192 if( $wgUser->isLoggedIn() ) {
1193 $this->permissionRequired( 'read' );
1197 $skin = $wgUser->getSkin();
1199 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1200 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1201 $this->setRobotPolicy( 'noindex,nofollow' );
1202 $this->setArticleFlag( false );
1204 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1205 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1206 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1207 $this->addHTML( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1209 # Don't return to the main page if the user can't read it
1210 # otherwise we'll end up in a pointless loop
1211 $mainPage = Title
::newMainPage();
1212 if( $mainPage->userCanRead() )
1213 $this->returnToMain( null, $mainPage );
1217 public function databaseError( $fname, $sql, $error, $errno ) {
1218 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1222 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1223 * @return string The wikitext error-messages, formatted into a list.
1225 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1226 if ($action == null) {
1227 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1230 $action_desc = wfMsg( "action-$action" );
1231 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1234 if (count( $errors ) > 1) {
1235 $text .= '<ul class="permissions-errors">' . "\n";
1237 foreach( $errors as $error )
1240 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1245 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1252 * Display a page stating that the Wiki is in read-only mode,
1253 * and optionally show the source of the page that the user
1254 * was trying to edit. Should only be called (for this
1255 * purpose) after wfReadOnly() has returned true.
1257 * For historical reasons, this function is _also_ used to
1258 * show the error message when a user tries to edit a page
1259 * they are not allowed to edit. (Unless it's because they're
1260 * blocked, then we show blockedPage() instead.) In this
1261 * case, the second parameter should be set to true and a list
1262 * of reasons supplied as the third parameter.
1264 * @todo Needs to be split into multiple functions.
1266 * @param string $source Source code to show (or null).
1267 * @param bool $protected Is this a permissions error?
1268 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1270 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1271 global $wgUser, $wgTitle;
1272 $skin = $wgUser->getSkin();
1274 $this->setRobotPolicy( 'noindex,nofollow' );
1275 $this->setArticleRelated( false );
1277 // If no reason is given, just supply a default "I can't let you do
1278 // that, Dave" message. Should only occur if called by legacy code.
1279 if ( $protected && empty($reasons) ) {
1280 $reasons[] = array( 'badaccess-group0' );
1283 if ( !empty($reasons) ) {
1284 // Permissions error
1286 $this->setPageTitle( wfMsg( 'viewsource' ) );
1287 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1289 $this->setPageTitle( wfMsg( 'badaccess' ) );
1291 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1293 // Wiki is read only
1294 $this->setPageTitle( wfMsg( 'readonly' ) );
1295 $reason = wfReadOnlyReason();
1296 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1299 // Show source, if supplied
1300 if( is_string( $source ) ) {
1301 $this->addWikiMsg( 'viewsourcetext' );
1302 $text = Xml
::openElement( 'textarea',
1303 array( 'id' => 'wpTextbox1',
1304 'name' => 'wpTextbox1',
1305 'cols' => $wgUser->getOption( 'cols' ),
1306 'rows' => $wgUser->getOption( 'rows' ),
1307 'readonly' => 'readonly' ) );
1308 $text .= htmlspecialchars( $source );
1309 $text .= Xml
::closeElement( 'textarea' );
1310 $this->addHTML( $text );
1312 // Show templates used by this article
1313 $skin = $wgUser->getSkin();
1314 $article = new Article( $wgTitle );
1315 $this->addHTML( "<div class='templatesUsed'>
1316 {$skin->formatTemplates( $article->getUsedTemplates() )}
1321 # If the title doesn't exist, it's fairly pointless to print a return
1322 # link to it. After all, you just tried editing it and couldn't, so
1323 # what's there to do there?
1324 if( $wgTitle->exists() ) {
1325 $this->returnToMain( null, $wgTitle );
1330 public function fatalError( $message ) {
1331 wfDeprecated( __METHOD__
);
1332 throw new FatalError( $message );
1336 public function unexpectedValueError( $name, $val ) {
1337 wfDeprecated( __METHOD__
);
1338 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1342 public function fileCopyError( $old, $new ) {
1343 wfDeprecated( __METHOD__
);
1344 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1348 public function fileRenameError( $old, $new ) {
1349 wfDeprecated( __METHOD__
);
1350 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1354 public function fileDeleteError( $name ) {
1355 wfDeprecated( __METHOD__
);
1356 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1360 public function fileNotFoundError( $name ) {
1361 wfDeprecated( __METHOD__
);
1362 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1365 public function showFatalError( $message ) {
1366 $this->setPageTitle( wfMsg( "internalerror" ) );
1367 $this->setRobotPolicy( "noindex,nofollow" );
1368 $this->setArticleRelated( false );
1369 $this->enableClientCache( false );
1370 $this->mRedirect
= '';
1371 $this->mBodytext
= $message;
1374 public function showUnexpectedValueError( $name, $val ) {
1375 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1378 public function showFileCopyError( $old, $new ) {
1379 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1382 public function showFileRenameError( $old, $new ) {
1383 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1386 public function showFileDeleteError( $name ) {
1387 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1390 public function showFileNotFoundError( $name ) {
1391 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1395 * Add a "return to" link pointing to a specified title
1397 * @param Title $title Title to link
1399 public function addReturnTo( $title ) {
1401 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1402 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1403 $this->addHTML( "<p>{$link}</p>\n" );
1407 * Add a "return to" link pointing to a specified title,
1408 * or the title indicated in the request, or else the main page
1410 * @param null $unused No longer used
1411 * @param Title $returnto Title to return to
1413 public function returnToMain( $unused = null, $returnto = NULL ) {
1416 if ( $returnto == NULL ) {
1417 $returnto = $wgRequest->getText( 'returnto' );
1420 if ( '' === $returnto ) {
1421 $returnto = Title
::newMainPage();
1424 if ( is_object( $returnto ) ) {
1425 $titleObj = $returnto;
1427 $titleObj = Title
::newFromText( $returnto );
1429 if ( !is_object( $titleObj ) ) {
1430 $titleObj = Title
::newMainPage();
1433 $this->addReturnTo( $titleObj );
1437 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1438 * and uses the first 10 of them for META keywords
1440 * @param ParserOutput &$parserOutput
1442 private function addKeywords( &$parserOutput ) {
1444 $this->addKeyword( $wgTitle->getPrefixedText() );
1446 $links2d =& $parserOutput->getLinks();
1447 if ( !is_array( $links2d ) ) {
1450 foreach ( $links2d as $dbkeys ) {
1451 foreach( $dbkeys as $dbkey => $unused ) {
1452 $this->addKeyword( $dbkey );
1453 if ( ++
$count > 10 ) {
1461 * @return string The doctype, opening <html>, and head element.
1463 public function headElement( Skin
$sk ) {
1464 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1465 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1466 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1468 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1469 $this->addStyle( 'common/wikiprintable.css', 'print' );
1470 $sk->setupUserCss( $this );
1474 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1475 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1478 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1480 if ( '' == $this->getHTMLTitle() ) {
1481 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1484 $rtl = $wgContLang->isRTL() ?
" dir='RTL'" : '';
1485 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1486 foreach($wgXhtmlNamespaces as $tag => $ns) {
1487 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1489 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1490 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t\t";
1491 $ret .= implode( "\t\t", array(
1492 $this->getHeadLinks(),
1493 $this->buildCssLinks(),
1494 $sk->getHeadScripts( $this->mAllowUserJs
),
1496 $this->getHeadItems(),
1499 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1502 if ($wgUseTrackbacks && $this->isArticleRelated())
1503 $ret .= $wgTitle->trackbackRDF();
1505 $ret .= "</head>\n";
1509 protected function addDefaultMeta() {
1511 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1512 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1514 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1515 if( $p !== 'index,follow' ) {
1516 // http://www.robotstxt.org/wc/meta-user.html
1517 // Only show if it's different from the default robots policy
1518 $this->addMeta( 'robots', $p );
1521 if ( count( $this->mKeywords
) > 0 ) {
1526 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1531 * @return string HTML tag links to be put in the header.
1533 public function getHeadLinks() {
1534 global $wgRequest, $wgFeed;
1536 // Ideally this should happen earlier, somewhere. :P
1537 $this->addDefaultMeta();
1541 foreach ( $this->mMetatags
as $tag ) {
1542 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1544 $tag[0] = substr( $tag[0], 5 );
1548 $tags[] = Xml
::element( 'meta',
1551 'content' => $tag[1] ) );
1553 foreach ( $this->mLinktags
as $tag ) {
1554 $tags[] = Xml
::element( 'link', $tag );
1559 foreach( $this->getSyndicationLinks() as $format => $link ) {
1560 # Use the page name for the title (accessed through $wgTitle since
1561 # there's no other way). In principle, this could lead to issues
1562 # with having the same name for different feeds corresponding to
1563 # the same page, but we can't avoid that at this low a level.
1565 $tags[] = $this->feedLink(
1568 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1571 # Recent changes feed should appear on every page (except recentchanges,
1572 # that would be redundant). Put it after the per-page feed to avoid
1573 # changing existing behavior. It's still available, probably via a
1574 # menu in your browser. Some sites might have a different feed they'd
1575 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1576 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1577 # If so, use it instead.
1579 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1580 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1582 if ( $wgOverrideSiteFeed ) {
1583 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1584 $tags[] = $this->feedLink (
1586 htmlspecialchars( $feedUrl ),
1587 wfMsg( "site-{$type}-feed", $wgSitename ) );
1590 else if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1591 foreach( $wgFeedClasses as $format => $class ) {
1592 $tags[] = $this->feedLink(
1594 $rctitle->getFullURL( "feed={$format}" ),
1595 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1600 return implode( "\n\t\t", $tags ) . "\n";
1604 * Return URLs for each supported syndication format for this page.
1605 * @return array associating format keys with URLs
1607 public function getSyndicationLinks() {
1608 global $wgTitle, $wgFeedClasses;
1611 if( $this->isSyndicated() ) {
1612 if( is_string( $this->getFeedAppendQuery() ) ) {
1613 $appendQuery = "&" . $this->getFeedAppendQuery();
1618 foreach( $wgFeedClasses as $format => $class ) {
1619 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1626 * Generate a <link rel/> for an RSS feed.
1628 private function feedLink( $type, $url, $text ) {
1629 return Xml
::element( 'link', array(
1630 'rel' => 'alternate',
1631 'type' => "application/$type+xml",
1637 * Add a local or specified stylesheet, with the given media options.
1638 * Meant primarily for internal use...
1640 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1641 * @param $conditional -- for IE conditional comments, specifying an IE version
1642 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1644 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1647 $options['media'] = $media;
1649 $options['condition'] = $condition;
1651 $options['dir'] = $dir;
1652 $this->styles
[$style] = $options;
1656 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1657 * These will be applied to various media & IE conditionals.
1659 public function buildCssLinks() {
1661 foreach( $this->styles
as $file => $options ) {
1662 $link = $this->styleLink( $file, $options );
1667 return implode( "\n\t\t", $links );
1670 protected function styleLink( $style, $options ) {
1673 if( isset( $options['dir'] ) ) {
1675 $siteDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1676 if( $siteDir != $options['dir'] )
1680 if( isset( $options['media'] ) ) {
1681 $media = $this->transformCssMedia( $options['media'] );
1682 if( is_null( $media ) ) {
1689 if( substr( $style, 0, 1 ) == '/' ||
1690 substr( $style, 0, 5 ) == 'http:' ||
1691 substr( $style, 0, 6 ) == 'https:' ) {
1694 global $wgStylePath, $wgStyleVersion;
1695 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1699 'rel' => 'stylesheet',
1701 'type' => 'text/css' );
1703 $attribs['media'] = $media;
1706 $link = Xml
::element( 'link', $attribs );
1708 if( isset( $options['condition'] ) ) {
1709 $condition = htmlspecialchars( $options['condition'] );
1710 $link = "<!--[if $condition]>$link<![endif]-->";
1715 function transformCssMedia( $media ) {
1716 global $wgRequest, $wgHandheldForIPhone;
1718 // Switch in on-screen display for media testing
1720 'printable' => 'print',
1721 'handheld' => 'handheld',
1723 foreach( $switches as $switch => $targetMedia ) {
1724 if( $wgRequest->getBool( $switch ) ) {
1725 if( $media == $targetMedia ) {
1727 } elseif( $media == 'screen' ) {
1733 // Expand longer media queries as iPhone doesn't grok 'handheld'
1734 if( $wgHandheldForIPhone ) {
1735 $mediaAliases = array(
1736 'screen' => 'screen and (min-device-width: 481px)',
1737 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1740 if( isset( $mediaAliases[$media] ) ) {
1741 $media = $mediaAliases[$media];
1749 * Turn off regular page output and return an error reponse
1750 * for when rate limiting has triggered.
1752 public function rateLimited() {
1755 $this->setPageTitle(wfMsg('actionthrottled'));
1756 $this->setRobotPolicy( 'noindex,follow' );
1757 $this->setArticleRelated( false );
1758 $this->enableClientCache( false );
1759 $this->mRedirect
= '';
1761 $this->setStatusCode(503);
1762 $this->addWikiMsg( 'actionthrottledtext' );
1764 $this->returnToMain( null, $wgTitle );
1768 * Show an "add new section" link?
1772 public function showNewSectionLink() {
1773 return $this->mNewSectionLink
;
1777 * Show a warning about slave lag
1779 * If the lag is higher than $wgSlaveLagCritical seconds,
1780 * then the warning is a bit more obvious. If the lag is
1781 * lower than $wgSlaveLagWarning, then no warning is shown.
1783 * @param int $lag Slave lag
1785 public function showLagWarning( $lag ) {
1786 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1787 if( $lag >= $wgSlaveLagWarning ) {
1788 $message = $lag < $wgSlaveLagCritical
1791 $warning = wfMsgExt( $message, 'parse', $lag );
1792 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1797 * Add a wikitext-formatted message to the output.
1798 * This is equivalent to:
1800 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1802 public function addWikiMsg( /*...*/ ) {
1803 $args = func_get_args();
1804 $name = array_shift( $args );
1805 $this->addWikiMsgArray( $name, $args );
1809 * Add a wikitext-formatted message to the output.
1810 * Like addWikiMsg() except the parameters are taken as an array
1811 * instead of a variable argument list.
1813 * $options is passed through to wfMsgExt(), see that function for details.
1815 public function addWikiMsgArray( $name, $args, $options = array() ) {
1816 $options[] = 'parse';
1817 $text = wfMsgExt( $name, $options, $args );
1818 $this->addHTML( $text );
1822 * This function takes a number of message/argument specifications, wraps them in
1823 * some overall structure, and then parses the result and adds it to the output.
1825 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1826 * on. The subsequent arguments may either be strings, in which case they are the
1827 * message names, or an arrays, in which case the first element is the message name,
1828 * and subsequent elements are the parameters to that message.
1830 * The special named parameter 'options' in a message specification array is passed
1831 * through to the $options parameter of wfMsgExt().
1833 * Don't use this for messages that are not in users interface language.
1837 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1841 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1843 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1844 $msgSpecs = func_get_args();
1845 array_shift( $msgSpecs );
1846 $msgSpecs = array_values( $msgSpecs );
1848 foreach ( $msgSpecs as $n => $spec ) {
1850 if ( is_array( $spec ) ) {
1852 $name = array_shift( $args );
1853 if ( isset( $args['options'] ) ) {
1854 $options = $args['options'];
1855 unset( $args['options'] );
1861 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
1863 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );