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 $mHideNewSectionLink = false;
33 var $mNoGallery = false;
34 var $mPageTitleActionText = '';
35 var $mParseWarnings = array();
36 var $mSquidMaxage = 0;
37 var $mRevisionId = null;
40 * An array of stylesheet filenames (relative from skins path), with options
41 * for CSS media, IE conditions, and RTL/LTR direction.
42 * For internal use; add settings in the skin via $this->addStyle()
44 var $styles = array();
46 private $mIndexPolicy = 'index';
47 private $mFollowPolicy = 'follow';
51 * Initialise private variables
53 function __construct() {
54 global $wgAllowUserJs;
55 $this->mAllowUserJs = $wgAllowUserJs;
58 public function redirect( $url, $responsecode = '302' ) {
59 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
60 $this->mRedirect = str_replace( "\n", '', $url );
61 $this->mRedirectCode = $responsecode;
64 public function getRedirect() {
65 return $this->mRedirect;
69 * Set the HTTP status code to send with the output.
71 * @param int $statusCode
74 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
77 * Add a new <meta> tag
78 * To add an http-equiv meta tag, precede the name with "http:"
80 * @param $name tag name
81 * @param $val tag value
83 function addMeta( $name, $val ) {
84 array_push( $this->mMetatags, array( $name, $val ) );
87 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
88 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
90 function addExtensionStyle( $url ) {
91 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
92 array_push( $this->mExtStyles, $linkarr );
96 * Add a JavaScript file out of skins/common, or a given relative path.
97 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
99 function addScriptFile( $file ) {
100 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
101 if( substr( $file, 0, 1 ) == '/' ) {
104 $path = "{$wgStylePath}/common/{$file}";
106 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"$path?$wgStyleVersion\"></script>\n" );
110 * Add a self-contained script tag with the given contents
111 * @param string $script JavaScript text, no <script> tags
113 function addInlineScript( $script ) {
114 global $wgJsMimeType;
115 $this->mScripts .= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
118 function getScript() {
119 return $this->mScripts . $this->getHeadItems();
122 function getHeadItems() {
124 foreach ( $this->mHeadItems as $item ) {
130 function addHeadItem( $name, $value ) {
131 $this->mHeadItems[$name] = $value;
134 function hasHeadItem( $name ) {
135 return isset( $this->mHeadItems[$name] );
138 function setETag($tag) { $this->mETag = $tag; }
139 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
140 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
142 function addLink( $linkarr ) {
143 # $linkarr should be an associative array of attributes. We'll escape on output.
144 array_push( $this->mLinktags, $linkarr );
147 # Get all links added by extensions
148 function getExtStyle() {
149 return $this->mExtStyles;
152 function addMetadataLink( $linkarr ) {
153 # note: buggy CC software only reads first "meta" link
154 static $haveMeta = false;
155 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
156 $this->addLink( $linkarr );
161 * checkLastModified tells the client to use the client-cached page if
162 * possible. If sucessful, the OutputPage is disabled so that
163 * any future call to OutputPage->output() have no effect.
165 * Side effect: sets mLastModified for Last-Modified header
167 * @return bool True iff cache-ok headers was sent.
169 function checkLastModified( $timestamp ) {
170 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
172 if ( !$timestamp || $timestamp == '19700101000000' ) {
173 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
176 if( !$wgCachePages ) {
177 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
180 if( $wgUser->getOption( 'nocache' ) ) {
181 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
185 $timestamp = wfTimestamp( TS_MW, $timestamp );
186 $modifiedTimes = array(
187 'page' => $timestamp,
188 'user' => $wgUser->getTouched(),
189 'epoch' => $wgCacheEpoch
191 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
193 $maxModified = max( $modifiedTimes );
194 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
196 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
197 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
203 foreach ( $modifiedTimes as $name => $value ) {
204 if ( $info !== '' ) {
207 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
210 # IE sends sizes after the date like this:
211 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
212 # this breaks strtotime().
213 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
215 wfSuppressWarnings(); // E_STRICT system time bitching
216 $clientHeaderTime = strtotime( $clientHeader );
218 if ( !$clientHeaderTime ) {
219 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
222 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
224 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
225 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
226 wfDebug( __METHOD__ . ": effective Last-Modified: " .
227 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
228 if( $clientHeaderTime < $maxModified ) {
229 wfDebug( __METHOD__ . ": STALE, $info\n", false );
234 # Give a 304 response code and disable body output
235 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
236 ini_set('zlib.output_compression', 0);
237 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
238 $this->sendCacheControl();
241 // Don't output a compressed blob when using ob_gzhandler;
242 // it's technically against HTTP spec and seems to confuse
243 // Firefox when the response gets split over two packets.
244 wfClearOutputBuffers();
249 function setPageTitleActionText( $text ) {
250 $this->mPageTitleActionText = $text;
253 function getPageTitleActionText () {
254 if ( isset( $this->mPageTitleActionText ) ) {
255 return $this->mPageTitleActionText;
260 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
262 * @param $policy string The literal string to output as the contents of
263 * the meta tag. Will be parsed according to the spec and output in
267 public function setRobotPolicy( $policy ) {
268 $policy = explode( ',', $policy );
269 $policy = array_map( 'trim', $policy );
271 # The default policy is follow, so if nothing is said explicitly, we
273 if( in_array( 'nofollow', $policy ) ) {
274 $this->mFollowPolicy = 'nofollow';
276 $this->mFollowPolicy = 'follow';
279 if( in_array( 'noindex', $policy ) ) {
280 $this->mIndexPolicy = 'noindex';
282 $this->mIndexPolicy = 'index';
287 * Set the index policy for the page, but leave the follow policy un-
290 * @param $policy string Either 'index' or 'noindex'.
293 public function setIndexPolicy( $policy ) {
294 $policy = trim( $policy );
295 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
296 $this->mIndexPolicy = $policy;
301 * Set the follow policy for the page, but leave the index policy un-
304 * @param $policy string Either 'follow' or 'nofollow'.
307 public function setFollowPolicy( $policy ) {
308 $policy = trim( $policy );
309 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
310 $this->mFollowPolicy = $policy;
314 public function setHTMLTitle( $name ) { $this->mHTMLtitle = $name; }
315 public function setPageTitle( $name ) {
317 $name = $wgContLang->convert( $name, true );
318 $this->mPagetitle = $name;
320 $taction = $this->getPageTitleActionText();
321 if( !empty( $taction ) ) {
322 $name .= ' - '.$taction;
325 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
328 public function getHTMLTitle() { return $this->mHTMLtitle; }
329 public function getPageTitle() { return $this->mPagetitle; }
330 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
331 public function appendSubtitle( $str ) { $this->mSubtitle .= /*$this->parse(*/$str/*)*/; } // @bug 2514
332 public function getSubtitle() { return $this->mSubtitle; }
333 public function isArticle() { return $this->mIsarticle; }
334 public function setPrintable() { $this->mPrintable = true; }
335 public function isPrintable() { return $this->mPrintable; }
336 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
337 public function isSyndicated() { return $this->mShowFeedLinks; }
338 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
339 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
340 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
341 public function getOnloadHandler() { return $this->mOnloadHandler; }
342 public function disable() { $this->mDoNothing = true; }
343 public function isDisabled() { return $this->mDoNothing; }
345 public function setArticleRelated( $v ) {
346 $this->mIsArticleRelated = $v;
348 $this->mIsarticle = false;
351 public function setArticleFlag( $v ) {
352 $this->mIsarticle = $v;
354 $this->mIsArticleRelated = $v;
358 public function isArticleRelated() { return $this->mIsArticleRelated; }
360 public function getLanguageLinks() { return $this->mLanguageLinks; }
361 public function addLanguageLinks($newLinkArray) {
362 $this->mLanguageLinks += $newLinkArray;
364 public function setLanguageLinks($newLinkArray) {
365 $this->mLanguageLinks = $newLinkArray;
368 public function getCategoryLinks() {
369 return $this->mCategoryLinks;
373 * Add an array of categories, with names in the keys
375 public function addCategoryLinks( $categories ) {
376 global $wgUser, $wgContLang;
378 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
382 # Add the links to a LinkBatch
383 $arr = array( NS_CATEGORY => $categories );
385 $lb->setArray( $arr );
387 # Fetch existence plus the hiddencat property
388 $dbr = wfGetDB( DB_SLAVE );
389 $pageTable = $dbr->tableName( 'page' );
390 $where = $lb->constructSet( 'page', $dbr );
391 $propsTable = $dbr->tableName( 'page_props' );
392 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
393 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
394 $res = $dbr->query( $sql, __METHOD__ );
396 # Add the results to the link cache
397 $lb->addResultToCache( LinkCache::singleton(), $res );
399 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
400 $categories = array_combine( array_keys( $categories ),
401 array_fill( 0, count( $categories ), 'normal' ) );
403 # Mark hidden categories
404 foreach ( $res as $row ) {
405 if ( isset( $row->pp_value ) ) {
406 $categories[$row->page_title] = 'hidden';
410 # Add the remaining categories to the skin
411 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
412 $sk = $wgUser->getSkin();
413 foreach ( $categories as $category => $type ) {
414 $origcategory = $category;
415 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
416 $wgContLang->findVariantLink( $category, $title, true );
417 if ( $category != $origcategory )
418 if ( array_key_exists( $category, $categories ) )
420 $text = $wgContLang->convertHtml( $title->getText() );
421 $this->mCategoryLinks[$type][] = $sk->makeLinkObj( $title, $text );
426 public function setCategoryLinks($categories) {
427 $this->mCategoryLinks = array();
428 $this->addCategoryLinks($categories);
431 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
432 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
434 public function disallowUserJs() { $this->mAllowUserJs = false; }
435 public function isUserJsAllowed() { return $this->mAllowUserJs; }
437 public function prependHTML( $text ) { $this->mBodytext = $text . $this->mBodytext; }
438 public function addHTML( $text ) { $this->mBodytext .= $text; }
439 public function clearHTML() { $this->mBodytext = ''; }
440 public function getHTML() { return $this->mBodytext; }
441 public function debug( $text ) { $this->mDebugtext .= $text; }
444 public function setParserOptions( $options ) {
445 wfDeprecated( __METHOD__ );
446 return $this->parserOptions( $options );
449 public function parserOptions( $options = null ) {
450 if ( !$this->mParserOptions ) {
451 $this->mParserOptions = new ParserOptions;
453 return wfSetVar( $this->mParserOptions, $options );
457 * Set the revision ID which will be seen by the wiki text parser
458 * for things such as embedded {{REVISIONID}} variable use.
459 * @param mixed $revid an integer, or NULL
460 * @return mixed previous value
462 public function setRevisionId( $revid ) {
463 $val = is_null( $revid ) ? null : intval( $revid );
464 return wfSetVar( $this->mRevisionId, $val );
467 public function getRevisionId() {
468 return $this->mRevisionId;
472 * Convert wikitext to HTML and add it to the buffer
473 * Default assumes that the current page title will
476 * @param string $text
477 * @param bool $linestart
479 public function addWikiText( $text, $linestart = true ) {
481 $this->addWikiTextTitle($text, $wgTitle, $linestart);
484 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
485 $this->addWikiTextTitle($text, $title, $linestart);
488 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
489 $this->addWikiTextTitle( $text, $title, $linestart, true );
492 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
495 wfProfileIn( __METHOD__ );
497 wfIncrStats( 'pcache_not_possible' );
499 $popts = $this->parserOptions();
500 $oldTidy = $popts->setTidy( $tidy );
502 $parserOutput = $wgParser->parse( $text, $title, $popts,
503 $linestart, true, $this->mRevisionId );
505 $popts->setTidy( $oldTidy );
507 $this->addParserOutput( $parserOutput );
509 wfProfileOut( __METHOD__ );
514 * @param ParserOutput object &$parserOutput
516 public function addParserOutputNoText( &$parserOutput ) {
517 global $wgTitle, $wgExemptFromUserRobotsControl, $wgContentNamespaces;
519 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
520 $this->addCategoryLinks( $parserOutput->getCategories() );
521 $this->mNewSectionLink = $parserOutput->getNewSection();
522 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
524 if( is_null( $wgExemptFromUserRobotsControl ) ) {
525 $bannedNamespaces = $wgContentNamespaces;
527 $bannedNamespaces = $wgExemptFromUserRobotsControl;
529 if( !in_array( $wgTitle->getNamespace(), $bannedNamespaces ) ) {
530 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
532 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
535 $this->addKeywords( $parserOutput );
536 $this->mParseWarnings = $parserOutput->getWarnings();
537 if ( $parserOutput->getCacheTime() == -1 ) {
538 $this->enableClientCache( false );
540 $this->mNoGallery = $parserOutput->getNoGallery();
541 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
543 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
544 if ( isset( $this->mTemplateIds[$ns] ) ) {
545 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
547 $this->mTemplateIds[$ns] = $dbks;
551 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
552 $this->setPageTitle( $dt );
553 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
554 $this->setPageTitle( $title );
556 // Hooks registered in the object
557 global $wgParserOutputHooks;
558 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
559 list( $hookName, $data ) = $hookInfo;
560 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
561 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
565 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
570 * @param ParserOutput &$parserOutput
572 function addParserOutput( &$parserOutput ) {
573 $this->addParserOutputNoText( $parserOutput );
574 $text = $parserOutput->getText();
575 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
576 $this->addHTML( $text );
580 * Add wikitext to the buffer, assuming that this is the primary text for a page view
581 * Saves the text into the parser cache if possible.
583 * @param string $text
584 * @param Article $article
586 * @deprecated Use Article::outputWikitext
588 public function addPrimaryWikiText( $text, $article, $cache = true ) {
589 global $wgParser, $wgUser;
591 wfDeprecated( __METHOD__ );
593 $popts = $this->parserOptions();
594 $popts->setTidy(true);
595 $parserOutput = $wgParser->parse( $text, $article->mTitle,
596 $popts, true, true, $this->mRevisionId );
597 $popts->setTidy(false);
598 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
599 $parserCache = ParserCache::singleton();
600 $parserCache->save( $parserOutput, $article, $popts);
603 $this->addParserOutput( $parserOutput );
607 * @deprecated use addWikiTextTidy()
609 public function addSecondaryWikiText( $text, $linestart = true ) {
611 wfDeprecated( __METHOD__ );
612 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
616 * Add wikitext with tidy enabled
618 public function addWikiTextTidy( $text, $linestart = true ) {
620 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
625 * Add the output of a QuickTemplate to the output buffer
627 * @param QuickTemplate $template
629 public function addTemplate( &$template ) {
631 $template->execute();
632 $this->addHTML( ob_get_contents() );
637 * Parse wikitext and return the HTML.
639 * @param string $text
640 * @param bool $linestart Is this the start of a line?
641 * @param bool $interface ??
643 public function parse( $text, $linestart = true, $interface = false ) {
644 global $wgParser, $wgTitle;
645 if( is_null( $wgTitle ) ) {
646 throw new MWException( 'Empty $wgTitle in ' . __METHOD__ );
648 $popts = $this->parserOptions();
649 if ( $interface) { $popts->setInterfaceMessage(true); }
650 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
651 $linestart, true, $this->mRevisionId );
652 if ( $interface) { $popts->setInterfaceMessage(false); }
653 return $parserOutput->getText();
656 /** Parse wikitext, strip paragraphs, and return the HTML. */
657 public function parseInline( $text, $linestart = true, $interface = false ) {
658 $parsed = $this->parse( $text, $linestart, $interface );
661 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
669 * @param Article $article
672 * @return bool True if successful, else false.
674 public function tryParserCache( &$article ) {
675 $parserCache = ParserCache::singleton();
676 $parserOutput = $parserCache->get( $article, $this->parserOptions() );
677 if ( $parserOutput !== false ) {
678 $this->addParserOutput( $parserOutput );
686 * @param int $maxage Maximum cache time on the Squid, in seconds.
688 public function setSquidMaxage( $maxage ) {
689 $this->mSquidMaxage = $maxage;
693 * Use enableClientCache(false) to force it to send nocache headers
696 public function enableClientCache( $state ) {
697 return wfSetVar( $this->mEnableClientCache, $state );
700 function getCacheVaryCookies() {
701 global $wgCookiePrefix, $wgCacheVaryCookies;
703 if ( $cookies === null ) {
704 $cookies = array_merge(
706 "{$wgCookiePrefix}Token",
707 "{$wgCookiePrefix}LoggedOut",
712 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
717 function uncacheableBecauseRequestVars() {
719 return $wgRequest->getText('useskin', false) === false
720 && $wgRequest->getText('uselang', false) === false;
724 * Check if the request has a cache-varying cookie header
725 * If it does, it's very important that we don't allow public caching
727 function haveCacheVaryCookies() {
729 $cookieHeader = $wgRequest->getHeader( 'cookie' );
730 if ( $cookieHeader === false ) {
733 $cvCookies = $this->getCacheVaryCookies();
734 foreach ( $cvCookies as $cookieName ) {
735 # Check for a simple string match, like the way squid does it
736 if ( strpos( $cookieHeader, $cookieName ) ) {
737 wfDebug( __METHOD__.": found $cookieName\n" );
741 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
745 /** Get a complete X-Vary-Options header */
746 public function getXVO() {
747 $cvCookies = $this->getCacheVaryCookies();
748 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
750 foreach ( $cvCookies as $cookieName ) {
756 $xvo .= 'string-contains=' . $cookieName;
761 public function sendCacheControl() {
762 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
764 $response = $wgRequest->response();
765 if ($wgUseETag && $this->mETag)
766 $response->header("ETag: $this->mETag");
768 # don't serve compressed data to clients who can't handle it
769 # maintain different caches for logged-in users and non-logged in ones
770 $response->header( 'Vary: Accept-Encoding, Cookie' );
772 # Add an X-Vary-Options header for Squid with Wikimedia patches
773 $response->header( $this->getXVO() );
775 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
776 if( $wgUseSquid && session_id() == '' &&
777 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
780 # We'll purge the proxy cache explicitly, but require end user agents
781 # to revalidate against the proxy on each visit.
782 # Surrogate-Control controls our Squid, Cache-Control downstream caches
783 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
784 # start with a shorter timeout for initial testing
785 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
786 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
787 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
789 # We'll purge the proxy cache for anons explicitly, but require end user agents
790 # to revalidate against the proxy on each visit.
791 # IMPORTANT! The Squid needs to replace the Cache-Control header with
792 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
793 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
794 # start with a shorter timeout for initial testing
795 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
796 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
799 # We do want clients to cache if they can, but they *must* check for updates
800 # on revisiting the page.
801 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
802 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
803 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
805 if($this->mLastModified) {
806 $response->header( "Last-Modified: {$this->mLastModified}" );
809 wfDebug( __METHOD__ . ": no caching **\n", false );
811 # In general, the absence of a last modified header should be enough to prevent
812 # the client from using its cache. We send a few other things just to make sure.
813 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
814 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
815 $response->header( 'Pragma: no-cache' );
820 * Finally, all the text has been munged and accumulated into
821 * the object, let's actually output it:
823 public function output() {
824 global $wgUser, $wgOutputEncoding, $wgRequest;
825 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
826 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
827 global $wgEnableMWSuggest, $wgUniversalEditButton;
828 global $wgArticle, $wgTitle;
830 if( $this->mDoNothing ){
834 wfProfileIn( __METHOD__ );
836 if ( '' != $this->mRedirect ) {
837 # Standards require redirect URLs to be absolute
838 $this->mRedirect = wfExpandUrl( $this->mRedirect );
839 if( $this->mRedirectCode == '301') {
840 if( !$wgDebugRedirects ) {
841 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
843 $this->mLastModified = wfTimestamp( TS_RFC2822 );
846 $this->sendCacheControl();
848 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
849 if( $wgDebugRedirects ) {
850 $url = htmlspecialchars( $this->mRedirect );
851 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
852 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
853 print "</body>\n</html>\n";
855 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
857 wfProfileOut( __METHOD__ );
860 elseif ( $this->mStatusCode )
862 $statusMessage = array(
864 101 => 'Switching Protocols',
869 203 => 'Non-Authoritative Information',
871 205 => 'Reset Content',
872 206 => 'Partial Content',
873 207 => 'Multi-Status',
874 300 => 'Multiple Choices',
875 301 => 'Moved Permanently',
878 304 => 'Not Modified',
880 307 => 'Temporary Redirect',
881 400 => 'Bad Request',
882 401 => 'Unauthorized',
883 402 => 'Payment Required',
886 405 => 'Method Not Allowed',
887 406 => 'Not Acceptable',
888 407 => 'Proxy Authentication Required',
889 408 => 'Request Timeout',
892 411 => 'Length Required',
893 412 => 'Precondition Failed',
894 413 => 'Request Entity Too Large',
895 414 => 'Request-URI Too Large',
896 415 => 'Unsupported Media Type',
897 416 => 'Request Range Not Satisfiable',
898 417 => 'Expectation Failed',
899 422 => 'Unprocessable Entity',
901 424 => 'Failed Dependency',
902 500 => 'Internal Server Error',
903 501 => 'Not Implemented',
904 502 => 'Bad Gateway',
905 503 => 'Service Unavailable',
906 504 => 'Gateway Timeout',
907 505 => 'HTTP Version Not Supported',
908 507 => 'Insufficient Storage'
911 if ( $statusMessage[$this->mStatusCode] )
912 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
915 $sk = $wgUser->getSkin();
918 $this->addScriptFile( 'ajax.js' );
920 wfRunHooks( 'AjaxAddScript', array( &$this ) );
922 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
923 $this->addScriptFile( 'ajaxwatch.js' );
926 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
927 $this->addScriptFile( 'mwsuggest.js' );
931 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
932 $this->addScriptFile( 'rightclickedit.js' );
935 if( $wgUniversalEditButton ) {
936 if( isset( $wgArticle ) && isset( $wgTitle ) && $wgTitle->quickUserCan( 'edit' )
937 && ( $wgTitle->exists() || $wgTitle->quickUserCan( 'create' ) ) ) {
938 // Original UniversalEditButton
939 $this->addLink( array(
940 'rel' => 'alternate',
941 'type' => 'application/x-wiki',
942 'title' => wfMsg( 'edit' ),
943 'href' => $wgTitle->getLocalURL( 'action=edit' )
945 // Alternate edit link
946 $this->addLink( array(
948 'title' => wfMsg( 'edit' ),
949 'href' => $wgTitle->getLocalURL( 'action=edit' )
954 # Buffer output; final headers may depend on later processing
957 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
958 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
960 if ($this->mArticleBodyOnly) {
961 $this->out($this->mBodytext);
963 // Hook that allows last minute changes to the output page, e.g.
964 // adding of CSS or Javascript by extensions.
965 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
967 wfProfileIn( 'Output-skin' );
968 $sk->outputPage( $this );
969 wfProfileOut( 'Output-skin' );
972 $this->sendCacheControl();
974 wfProfileOut( __METHOD__ );
981 public function out( $ins ) {
982 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
983 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
986 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
987 if ( false === $outs ) { $outs = $ins; }
995 public static function setEncodings() {
996 global $wgInputEncoding, $wgOutputEncoding;
997 global $wgUser, $wgContLang;
999 $wgInputEncoding = strtolower( $wgInputEncoding );
1001 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1002 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1005 $wgOutputEncoding = $wgInputEncoding;
1009 * Deprecated, use wfReportTime() instead.
1013 public function reportTime() {
1014 wfDeprecated( __METHOD__ );
1015 $time = wfReportTime();
1020 * Produce a "user is blocked" page.
1022 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1025 function blockedPage( $return = true ) {
1026 global $wgUser, $wgContLang, $wgTitle, $wgLang;
1028 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1029 $this->setRobotPolicy( 'noindex,nofollow' );
1030 $this->setArticleRelated( false );
1032 $name = User::whoIs( $wgUser->blockedBy() );
1033 $reason = $wgUser->blockedFor();
1034 if( $reason == '' ) {
1035 $reason = wfMsg( 'blockednoreason' );
1037 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1040 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1042 $blockid = $wgUser->mBlock->mId;
1044 $blockExpiry = $wgUser->mBlock->mExpiry;
1045 if ( $blockExpiry == 'infinity' ) {
1046 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1047 // Search for localization in 'ipboptions'
1048 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1049 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1050 if ( strpos( $option, ":" ) === false )
1052 list( $show, $value ) = explode( ":", $option );
1053 if ( $value == 'infinite' || $value == 'indefinite' ) {
1054 $blockExpiry = $show;
1059 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1062 if ( $wgUser->mBlock->mAuto ) {
1063 $msg = 'autoblockedtext';
1065 $msg = 'blockedtext';
1068 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1069 * This could be a username, an ip range, or a single ip. */
1070 $intended = $wgUser->mBlock->mAddress;
1072 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1074 # Don't auto-return to special pages
1076 $return = $wgTitle->getNamespace() > -1 ? $wgTitle : NULL;
1077 $this->returnToMain( null, $return );
1082 * Output a standard error page
1084 * @param string $title Message key for page title
1085 * @param string $msg Message key for page text
1086 * @param array $params Message parameters
1088 public function showErrorPage( $title, $msg, $params = array() ) {
1090 if ( isset($wgTitle) ) {
1091 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
1093 $this->setPageTitle( wfMsg( $title ) );
1094 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1095 $this->setRobotPolicy( 'noindex,nofollow' );
1096 $this->setArticleRelated( false );
1097 $this->enableClientCache( false );
1098 $this->mRedirect = '';
1099 $this->mBodytext = '';
1101 array_unshift( $params, 'parse' );
1102 array_unshift( $params, $msg );
1103 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1105 $this->returnToMain();
1109 * Output a standard permission error page
1111 * @param array $errors Error message keys
1113 public function showPermissionsErrorPage( $errors, $action = null )
1117 $this->mDebugtext .= 'Original title: ' .
1118 $wgTitle->getPrefixedText() . "\n";
1119 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1120 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1121 $this->setRobotPolicy( 'noindex,nofollow' );
1122 $this->setArticleRelated( false );
1123 $this->enableClientCache( false );
1124 $this->mRedirect = '';
1125 $this->mBodytext = '';
1126 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1130 public function errorpage( $title, $msg ) {
1131 wfDeprecated( __METHOD__ );
1132 throw new ErrorPageError( $title, $msg );
1136 * Display an error page indicating that a given version of MediaWiki is
1137 * required to use it
1139 * @param mixed $version The version of MediaWiki needed to use the page
1141 public function versionRequired( $version ) {
1142 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1143 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1144 $this->setRobotPolicy( 'noindex,nofollow' );
1145 $this->setArticleRelated( false );
1146 $this->mBodytext = '';
1148 $this->addWikiMsg( 'versionrequiredtext', $version );
1149 $this->returnToMain();
1153 * Display an error page noting that a given permission bit is required.
1155 * @param string $permission key required
1157 public function permissionRequired( $permission ) {
1158 global $wgUser, $wgLang;
1160 $this->setPageTitle( wfMsg( 'badaccess' ) );
1161 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1162 $this->setRobotPolicy( 'noindex,nofollow' );
1163 $this->setArticleRelated( false );
1164 $this->mBodytext = '';
1166 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1167 User::getGroupsWithPermission( $permission ) );
1169 $this->addWikiMsg( 'badaccess-groups',
1170 $wgLang->commaList( $groups ),
1173 $this->addWikiMsg( 'badaccess-group0' );
1175 $this->returnToMain();
1179 * Use permissionRequired.
1182 public function sysopRequired() {
1183 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1187 * Use permissionRequired.
1190 public function developerRequired() {
1191 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1195 * Produce the stock "please login to use the wiki" page
1197 public function loginToUse() {
1198 global $wgUser, $wgTitle, $wgContLang;
1200 if( $wgUser->isLoggedIn() ) {
1201 $this->permissionRequired( 'read' );
1205 $skin = $wgUser->getSkin();
1207 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1208 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1209 $this->setRobotPolicy( 'noindex,nofollow' );
1210 $this->setArticleFlag( false );
1212 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1213 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1214 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1215 $this->addHTML( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1217 # Don't return to the main page if the user can't read it
1218 # otherwise we'll end up in a pointless loop
1219 $mainPage = Title::newMainPage();
1220 if( $mainPage->userCanRead() )
1221 $this->returnToMain( null, $mainPage );
1225 public function databaseError( $fname, $sql, $error, $errno ) {
1226 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1230 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1231 * @return string The wikitext error-messages, formatted into a list.
1233 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1234 if ($action == null) {
1235 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1238 $action_desc = wfMsg( "action-$action" );
1239 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1242 if (count( $errors ) > 1) {
1243 $text .= '<ul class="permissions-errors">' . "\n";
1245 foreach( $errors as $error )
1248 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1253 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1260 * Display a page stating that the Wiki is in read-only mode,
1261 * and optionally show the source of the page that the user
1262 * was trying to edit. Should only be called (for this
1263 * purpose) after wfReadOnly() has returned true.
1265 * For historical reasons, this function is _also_ used to
1266 * show the error message when a user tries to edit a page
1267 * they are not allowed to edit. (Unless it's because they're
1268 * blocked, then we show blockedPage() instead.) In this
1269 * case, the second parameter should be set to true and a list
1270 * of reasons supplied as the third parameter.
1272 * @todo Needs to be split into multiple functions.
1274 * @param string $source Source code to show (or null).
1275 * @param bool $protected Is this a permissions error?
1276 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1278 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1279 global $wgUser, $wgTitle;
1280 $skin = $wgUser->getSkin();
1282 $this->setRobotPolicy( 'noindex,nofollow' );
1283 $this->setArticleRelated( false );
1285 // If no reason is given, just supply a default "I can't let you do
1286 // that, Dave" message. Should only occur if called by legacy code.
1287 if ( $protected && empty($reasons) ) {
1288 $reasons[] = array( 'badaccess-group0' );
1291 if ( !empty($reasons) ) {
1292 // Permissions error
1294 $this->setPageTitle( wfMsg( 'viewsource' ) );
1295 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1297 $this->setPageTitle( wfMsg( 'badaccess' ) );
1299 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1301 // Wiki is read only
1302 $this->setPageTitle( wfMsg( 'readonly' ) );
1303 $reason = wfReadOnlyReason();
1304 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1307 // Show source, if supplied
1308 if( is_string( $source ) ) {
1309 $this->addWikiMsg( 'viewsourcetext' );
1310 $text = Xml::openElement( 'textarea',
1311 array( 'id' => 'wpTextbox1',
1312 'name' => 'wpTextbox1',
1313 'cols' => $wgUser->getOption( 'cols' ),
1314 'rows' => $wgUser->getOption( 'rows' ),
1315 'readonly' => 'readonly' ) );
1316 $text .= htmlspecialchars( $source );
1317 $text .= Xml::closeElement( 'textarea' );
1318 $this->addHTML( $text );
1320 // Show templates used by this article
1321 $skin = $wgUser->getSkin();
1322 $article = new Article( $wgTitle );
1323 $this->addHTML( "<div class='templatesUsed'>
1324 {$skin->formatTemplates( $article->getUsedTemplates() )}
1329 # If the title doesn't exist, it's fairly pointless to print a return
1330 # link to it. After all, you just tried editing it and couldn't, so
1331 # what's there to do there?
1332 if( $wgTitle->exists() ) {
1333 $this->returnToMain( null, $wgTitle );
1338 public function fatalError( $message ) {
1339 wfDeprecated( __METHOD__ );
1340 throw new FatalError( $message );
1344 public function unexpectedValueError( $name, $val ) {
1345 wfDeprecated( __METHOD__ );
1346 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1350 public function fileCopyError( $old, $new ) {
1351 wfDeprecated( __METHOD__ );
1352 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1356 public function fileRenameError( $old, $new ) {
1357 wfDeprecated( __METHOD__ );
1358 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1362 public function fileDeleteError( $name ) {
1363 wfDeprecated( __METHOD__ );
1364 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1368 public function fileNotFoundError( $name ) {
1369 wfDeprecated( __METHOD__ );
1370 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1373 public function showFatalError( $message ) {
1374 $this->setPageTitle( wfMsg( "internalerror" ) );
1375 $this->setRobotPolicy( "noindex,nofollow" );
1376 $this->setArticleRelated( false );
1377 $this->enableClientCache( false );
1378 $this->mRedirect = '';
1379 $this->mBodytext = $message;
1382 public function showUnexpectedValueError( $name, $val ) {
1383 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1386 public function showFileCopyError( $old, $new ) {
1387 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1390 public function showFileRenameError( $old, $new ) {
1391 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1394 public function showFileDeleteError( $name ) {
1395 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1398 public function showFileNotFoundError( $name ) {
1399 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1403 * Add a "return to" link pointing to a specified title
1405 * @param Title $title Title to link
1407 public function addReturnTo( $title ) {
1409 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1410 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1411 $this->addHTML( "<p>{$link}</p>\n" );
1415 * Add a "return to" link pointing to a specified title,
1416 * or the title indicated in the request, or else the main page
1418 * @param null $unused No longer used
1419 * @param Title $returnto Title to return to
1421 public function returnToMain( $unused = null, $returnto = NULL ) {
1424 if ( $returnto == NULL ) {
1425 $returnto = $wgRequest->getText( 'returnto' );
1428 if ( '' === $returnto ) {
1429 $returnto = Title::newMainPage();
1432 if ( is_object( $returnto ) ) {
1433 $titleObj = $returnto;
1435 $titleObj = Title::newFromText( $returnto );
1437 if ( !is_object( $titleObj ) ) {
1438 $titleObj = Title::newMainPage();
1441 $this->addReturnTo( $titleObj );
1445 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1446 * and uses the first 10 of them for META keywords
1448 * @param ParserOutput &$parserOutput
1450 private function addKeywords( &$parserOutput ) {
1452 $this->addKeyword( $wgTitle->getPrefixedText() );
1454 $links2d =& $parserOutput->getLinks();
1455 if ( !is_array( $links2d ) ) {
1458 foreach ( $links2d as $dbkeys ) {
1459 foreach( $dbkeys as $dbkey => $unused ) {
1460 $this->addKeyword( $dbkey );
1461 if ( ++$count > 10 ) {
1469 * @return string The doctype, opening <html>, and head element.
1471 public function headElement( Skin $sk ) {
1472 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1473 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1474 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1476 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1477 $this->addStyle( 'common/wikiprintable.css', 'print' );
1478 $sk->setupUserCss( $this );
1482 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1483 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1486 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1488 if ( '' == $this->getHTMLTitle() ) {
1489 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1492 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1493 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1494 foreach($wgXhtmlNamespaces as $tag => $ns) {
1495 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1497 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1498 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t\t";
1499 $ret .= implode( "\t\t", array(
1500 $this->getHeadLinks(),
1501 $this->buildCssLinks(),
1502 $sk->getHeadScripts( $this->mAllowUserJs ),
1504 $this->getHeadItems(),
1507 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1510 if ($wgUseTrackbacks && $this->isArticleRelated())
1511 $ret .= $wgTitle->trackbackRDF();
1513 $ret .= "</head>\n";
1517 protected function addDefaultMeta() {
1519 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1520 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1522 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1523 if( $p !== 'index,follow' ) {
1524 // http://www.robotstxt.org/wc/meta-user.html
1525 // Only show if it's different from the default robots policy
1526 $this->addMeta( 'robots', $p );
1529 if ( count( $this->mKeywords ) > 0 ) {
1531 "/<.*?" . ">/" => '',
1534 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1539 * @return string HTML tag links to be put in the header.
1541 public function getHeadLinks() {
1542 global $wgRequest, $wgFeed;
1544 // Ideally this should happen earlier, somewhere. :P
1545 $this->addDefaultMeta();
1549 foreach ( $this->mMetatags as $tag ) {
1550 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1552 $tag[0] = substr( $tag[0], 5 );
1556 $tags[] = Xml::element( 'meta',
1559 'content' => $tag[1] ) );
1561 foreach ( $this->mLinktags as $tag ) {
1562 $tags[] = Xml::element( 'link', $tag );
1567 foreach( $this->getSyndicationLinks() as $format => $link ) {
1568 # Use the page name for the title (accessed through $wgTitle since
1569 # there's no other way). In principle, this could lead to issues
1570 # with having the same name for different feeds corresponding to
1571 # the same page, but we can't avoid that at this low a level.
1573 $tags[] = $this->feedLink(
1576 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1579 # Recent changes feed should appear on every page (except recentchanges,
1580 # that would be redundant). Put it after the per-page feed to avoid
1581 # changing existing behavior. It's still available, probably via a
1582 # menu in your browser. Some sites might have a different feed they'd
1583 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1584 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1585 # If so, use it instead.
1587 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1588 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1590 if ( $wgOverrideSiteFeed ) {
1591 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1592 $tags[] = $this->feedLink (
1594 htmlspecialchars( $feedUrl ),
1595 wfMsg( "site-{$type}-feed", $wgSitename ) );
1598 else if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1599 foreach( $wgFeedClasses as $format => $class ) {
1600 $tags[] = $this->feedLink(
1602 $rctitle->getLocalURL( "feed={$format}" ),
1603 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1608 return implode( "\n\t\t", $tags ) . "\n";
1612 * Return URLs for each supported syndication format for this page.
1613 * @return array associating format keys with URLs
1615 public function getSyndicationLinks() {
1616 global $wgTitle, $wgFeedClasses;
1619 if( $this->isSyndicated() ) {
1620 if( is_string( $this->getFeedAppendQuery() ) ) {
1621 $appendQuery = "&" . $this->getFeedAppendQuery();
1626 foreach( $wgFeedClasses as $format => $class ) {
1627 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1634 * Generate a <link rel/> for an RSS feed.
1636 private function feedLink( $type, $url, $text ) {
1637 return Xml::element( 'link', array(
1638 'rel' => 'alternate',
1639 'type' => "application/$type+xml",
1645 * Add a local or specified stylesheet, with the given media options.
1646 * Meant primarily for internal use...
1648 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1649 * @param $conditional -- for IE conditional comments, specifying an IE version
1650 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1652 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1655 $options['media'] = $media;
1657 $options['condition'] = $condition;
1659 $options['dir'] = $dir;
1660 $this->styles[$style] = $options;
1664 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1665 * These will be applied to various media & IE conditionals.
1667 public function buildCssLinks() {
1669 foreach( $this->styles as $file => $options ) {
1670 $link = $this->styleLink( $file, $options );
1675 return implode( "\n\t\t", $links );
1678 protected function styleLink( $style, $options ) {
1681 if( isset( $options['dir'] ) ) {
1683 $siteDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1684 if( $siteDir != $options['dir'] )
1688 if( isset( $options['media'] ) ) {
1689 $media = $this->transformCssMedia( $options['media'] );
1690 if( is_null( $media ) ) {
1697 if( substr( $style, 0, 1 ) == '/' ||
1698 substr( $style, 0, 5 ) == 'http:' ||
1699 substr( $style, 0, 6 ) == 'https:' ) {
1702 global $wgStylePath, $wgStyleVersion;
1703 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1707 'rel' => 'stylesheet',
1709 'type' => 'text/css' );
1711 $attribs['media'] = $media;
1714 $link = Xml::element( 'link', $attribs );
1716 if( isset( $options['condition'] ) ) {
1717 $condition = htmlspecialchars( $options['condition'] );
1718 $link = "<!--[if $condition]>$link<![endif]-->";
1723 function transformCssMedia( $media ) {
1724 global $wgRequest, $wgHandheldForIPhone;
1726 // Switch in on-screen display for media testing
1728 'printable' => 'print',
1729 'handheld' => 'handheld',
1731 foreach( $switches as $switch => $targetMedia ) {
1732 if( $wgRequest->getBool( $switch ) ) {
1733 if( $media == $targetMedia ) {
1735 } elseif( $media == 'screen' ) {
1741 // Expand longer media queries as iPhone doesn't grok 'handheld'
1742 if( $wgHandheldForIPhone ) {
1743 $mediaAliases = array(
1744 'screen' => 'screen and (min-device-width: 481px)',
1745 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1748 if( isset( $mediaAliases[$media] ) ) {
1749 $media = $mediaAliases[$media];
1757 * Turn off regular page output and return an error reponse
1758 * for when rate limiting has triggered.
1760 public function rateLimited() {
1763 $this->setPageTitle(wfMsg('actionthrottled'));
1764 $this->setRobotPolicy( 'noindex,follow' );
1765 $this->setArticleRelated( false );
1766 $this->enableClientCache( false );
1767 $this->mRedirect = '';
1769 $this->setStatusCode(503);
1770 $this->addWikiMsg( 'actionthrottledtext' );
1772 $this->returnToMain( null, $wgTitle );
1776 * Show an "add new section" link?
1780 public function showNewSectionLink() {
1781 return $this->mNewSectionLink;
1785 * Forcibly hide the new section link?
1789 public function forceHideNewSectionLink() {
1790 return $this->mHideNewSectionLink;
1794 * Show a warning about slave lag
1796 * If the lag is higher than $wgSlaveLagCritical seconds,
1797 * then the warning is a bit more obvious. If the lag is
1798 * lower than $wgSlaveLagWarning, then no warning is shown.
1800 * @param int $lag Slave lag
1802 public function showLagWarning( $lag ) {
1803 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1804 if( $lag >= $wgSlaveLagWarning ) {
1805 $message = $lag < $wgSlaveLagCritical
1808 $warning = wfMsgExt( $message, 'parse', $lag );
1809 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1814 * Add a wikitext-formatted message to the output.
1815 * This is equivalent to:
1817 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1819 public function addWikiMsg( /*...*/ ) {
1820 $args = func_get_args();
1821 $name = array_shift( $args );
1822 $this->addWikiMsgArray( $name, $args );
1826 * Add a wikitext-formatted message to the output.
1827 * Like addWikiMsg() except the parameters are taken as an array
1828 * instead of a variable argument list.
1830 * $options is passed through to wfMsgExt(), see that function for details.
1832 public function addWikiMsgArray( $name, $args, $options = array() ) {
1833 $options[] = 'parse';
1834 $text = wfMsgExt( $name, $options, $args );
1835 $this->addHTML( $text );
1839 * This function takes a number of message/argument specifications, wraps them in
1840 * some overall structure, and then parses the result and adds it to the output.
1842 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1843 * on. The subsequent arguments may either be strings, in which case they are the
1844 * message names, or an arrays, in which case the first element is the message name,
1845 * and subsequent elements are the parameters to that message.
1847 * The special named parameter 'options' in a message specification array is passed
1848 * through to the $options parameter of wfMsgExt().
1850 * Don't use this for messages that are not in users interface language.
1854 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1858 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1860 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1861 $msgSpecs = func_get_args();
1862 array_shift( $msgSpecs );
1863 $msgSpecs = array_values( $msgSpecs );
1865 foreach ( $msgSpecs as $n => $spec ) {
1867 if ( is_array( $spec ) ) {
1869 $name = array_shift( $args );
1870 if ( isset( $args['options'] ) ) {
1871 $options = $args['options'];
1872 unset( $args['options'] );
1878 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
1880 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );