Fix for r38784: force the noconvertlink toggle to be marked as used, otherwise it...
[mediawiki.git] / includes / OutputPage.php
blob9fcac1b3c1d00af6f16aaab17755618f07abadef
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
5 /**
6 * @todo document
7 */
8 class OutputPage {
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();
19 var $mAllowUserJs;
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;
38 private $mIndexPolicy = 'index';
39 private $mFollowPolicy = 'follow';
41 /**
42 * Constructor
43 * Initialise private variables
45 function __construct() {
46 global $wgAllowUserJs;
47 $this->mAllowUserJs = $wgAllowUserJs;
50 public function redirect( $url, $responsecode = '302' ) {
51 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
52 $this->mRedirect = str_replace( "\n", '', $url );
53 $this->mRedirectCode = $responsecode;
56 public function getRedirect() {
57 return $this->mRedirect;
60 /**
61 * Set the HTTP status code to send with the output.
63 * @param int $statusCode
64 * @return nothing
66 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
68 # To add an http-equiv meta tag, precede the name with "http:"
69 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
70 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
71 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
72 function addStyle( $style ) {
73 global $wgStylePath, $wgStyleVersion;
74 $this->addLink(
75 array(
76 'rel' => 'stylesheet',
77 'href' => $wgStylePath . '/' . $style . '?' . $wgStyleVersion,
78 'type' => 'text/css' ) );
81 function addExtensionStyle( $url ) {
82 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
83 array_push( $this->mExtStyles, $linkarr );
86 /**
87 * Add a JavaScript file out of skins/common, or a given relative path.
88 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
90 function addScriptFile( $file ) {
91 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
92 if( substr( $file, 0, 1 ) == '/' ) {
93 $path = $file;
94 } else {
95 $path = "{$wgStylePath}/common/{$file}";
97 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"$path?$wgStyleVersion\"></script>\n" );
101 * Add a self-contained script tag with the given contents
102 * @param string $script JavaScript text, no <script> tags
104 function addInlineScript( $script ) {
105 global $wgJsMimeType;
106 $this->mScripts .= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
109 function getScript() {
110 return $this->mScripts . $this->getHeadItems();
113 function getHeadItems() {
114 $s = '';
115 foreach ( $this->mHeadItems as $item ) {
116 $s .= $item;
118 return $s;
121 function addHeadItem( $name, $value ) {
122 $this->mHeadItems[$name] = $value;
125 function hasHeadItem( $name ) {
126 return isset( $this->mHeadItems[$name] );
129 function setETag($tag) { $this->mETag = $tag; }
130 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
131 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
133 function addLink( $linkarr ) {
134 # $linkarr should be an associative array of attributes. We'll escape on output.
135 array_push( $this->mLinktags, $linkarr );
138 # Get all links added by extensions
139 function getExtStyle() {
140 return $this->mExtStyles;
143 function addMetadataLink( $linkarr ) {
144 # note: buggy CC software only reads first "meta" link
145 static $haveMeta = false;
146 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
147 $this->addLink( $linkarr );
148 $haveMeta = true;
152 * checkLastModified tells the client to use the client-cached page if
153 * possible. If sucessful, the OutputPage is disabled so that
154 * any future call to OutputPage->output() have no effect.
156 * @return bool True iff cache-ok headers was sent.
158 function checkLastModified ( $timestamp ) {
159 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
161 if ( !$timestamp || $timestamp == '19700101000000' ) {
162 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
163 return;
165 if( !$wgCachePages ) {
166 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
167 return;
169 if( $wgUser->getOption( 'nocache' ) ) {
170 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
171 return;
174 $timestamp=wfTimestamp(TS_MW,$timestamp);
175 $lastmod = wfTimestamp( TS_RFC2822, max( $timestamp, $wgUser->mTouched, $wgCacheEpoch ) );
177 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
178 # IE sends sizes after the date like this:
179 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
180 # this breaks strtotime().
181 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
183 wfSuppressWarnings(); // E_STRICT system time bitching
184 $modsinceTime = strtotime( $modsince );
185 wfRestoreWarnings();
187 $ismodsince = wfTimestamp( TS_MW, $modsinceTime ? $modsinceTime : 1 );
188 wfDebug( __METHOD__ . ": -- client send If-Modified-Since: " . $modsince . "\n", false );
189 wfDebug( __METHOD__ . ": -- we might send Last-Modified : $lastmod\n", false );
190 if( ($ismodsince >= $timestamp ) && $wgUser->validateCache( $ismodsince ) && $ismodsince >= $wgCacheEpoch ) {
191 # Make sure you're in a place you can leave when you call us!
192 $wgRequest->response()->header( "HTTP/1.0 304 Not Modified" );
193 $this->mLastModified = $lastmod;
194 $this->sendCacheControl();
195 wfDebug( __METHOD__ . ": CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
196 $this->disable();
198 // Don't output a compressed blob when using ob_gzhandler;
199 // it's technically against HTTP spec and seems to confuse
200 // Firefox when the response gets split over two packets.
201 wfClearOutputBuffers();
203 return true;
204 } else {
205 wfDebug( __METHOD__ . ": READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
206 $this->mLastModified = $lastmod;
208 } else {
209 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
210 $this->mLastModified = $lastmod;
214 function setPageTitleActionText( $text ) {
215 $this->mPageTitleActionText = $text;
218 function getPageTitleActionText () {
219 if ( isset( $this->mPageTitleActionText ) ) {
220 return $this->mPageTitleActionText;
225 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
227 * @param $policy string The literal string to output as the contents of
228 * the meta tag. Will be parsed according to the spec and output in
229 * standardized form.
230 * @return null
232 public function setRobotPolicy( $policy ) {
233 $policy = explode( ',', $policy );
234 $policy = array_map( 'trim', $policy );
236 # The default policy is follow, so if nothing is said explicitly, we
237 # do that.
238 if( in_array( 'nofollow', $policy ) ) {
239 $this->mFollowPolicy = 'nofollow';
240 } else {
241 $this->mFollowPolicy = 'follow';
244 if( in_array( 'noindex', $policy ) ) {
245 $this->mIndexPolicy = 'noindex';
246 } else {
247 $this->mIndexPolicy = 'index';
252 * Set the index policy for the page, but leave the follow policy un-
253 * touched.
255 * @param $policy string Either 'index' or 'noindex'.
256 * @return null
258 public function setIndexPolicy( $policy ) {
259 $policy = trim( $policy );
260 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
261 $this->mIndexPolicy = $policy;
266 * Set the follow policy for the page, but leave the index policy un-
267 * touched.
269 * @param $policy string Either 'follow' or 'nofollow'.
270 * @return null
272 public function setFollowPolicy( $policy ) {
273 $policy = trim( $policy );
274 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
275 $this->mFollowPolicy = $policy;
279 public function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
280 public function setPageTitle( $name ) {
281 global $action, $wgContLang;
282 $name = $wgContLang->convert($name, true);
283 $this->mPagetitle = $name;
284 if(!empty($action)) {
285 $taction = $this->getPageTitleActionText();
286 if( !empty( $taction ) ) {
287 $name .= ' - '.$taction;
291 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
293 public function getHTMLTitle() { return $this->mHTMLtitle; }
294 public function getPageTitle() { return $this->mPagetitle; }
295 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
296 public function appendSubtitle( $str ) { $this->mSubtitle .= /*$this->parse(*/$str/*)*/; } // @bug 2514
297 public function getSubtitle() { return $this->mSubtitle; }
298 public function isArticle() { return $this->mIsarticle; }
299 public function setPrintable() { $this->mPrintable = true; }
300 public function isPrintable() { return $this->mPrintable; }
301 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
302 public function isSyndicated() { return $this->mShowFeedLinks; }
303 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
304 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
305 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
306 public function getOnloadHandler() { return $this->mOnloadHandler; }
307 public function disable() { $this->mDoNothing = true; }
309 public function setArticleRelated( $v ) {
310 $this->mIsArticleRelated = $v;
311 if ( !$v ) {
312 $this->mIsarticle = false;
315 public function setArticleFlag( $v ) {
316 $this->mIsarticle = $v;
317 if ( $v ) {
318 $this->mIsArticleRelated = $v;
322 public function isArticleRelated() { return $this->mIsArticleRelated; }
324 public function getLanguageLinks() { return $this->mLanguageLinks; }
325 public function addLanguageLinks($newLinkArray) {
326 $this->mLanguageLinks += $newLinkArray;
328 public function setLanguageLinks($newLinkArray) {
329 $this->mLanguageLinks = $newLinkArray;
332 public function getCategoryLinks() {
333 return $this->mCategoryLinks;
337 * Add an array of categories, with names in the keys
339 public function addCategoryLinks( $categories ) {
340 global $wgUser, $wgContLang;
342 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
343 return;
346 # Add the links to a LinkBatch
347 $arr = array( NS_CATEGORY => $categories );
348 $lb = new LinkBatch;
349 $lb->setArray( $arr );
351 # Fetch existence plus the hiddencat property
352 $dbr = wfGetDB( DB_SLAVE );
353 $pageTable = $dbr->tableName( 'page' );
354 $where = $lb->constructSet( 'page', $dbr );
355 $propsTable = $dbr->tableName( 'page_props' );
356 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
357 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
358 $res = $dbr->query( $sql, __METHOD__ );
360 # Add the results to the link cache
361 $lb->addResultToCache( LinkCache::singleton(), $res );
363 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
364 $categories = array_combine( array_keys( $categories ),
365 array_fill( 0, count( $categories ), 'normal' ) );
367 # Mark hidden categories
368 foreach ( $res as $row ) {
369 if ( isset( $row->pp_value ) ) {
370 $categories[$row->page_title] = 'hidden';
374 # Add the remaining categories to the skin
375 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
376 $sk = $wgUser->getSkin();
377 foreach ( $categories as $category => $type ) {
378 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
379 $text = $wgContLang->convertHtml( $title->getText() );
380 $this->mCategoryLinks[$type][] = $sk->makeLinkObj( $title, $text );
385 public function setCategoryLinks($categories) {
386 $this->mCategoryLinks = array();
387 $this->addCategoryLinks($categories);
390 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
391 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
393 public function disallowUserJs() { $this->mAllowUserJs = false; }
394 public function isUserJsAllowed() { return $this->mAllowUserJs; }
396 public function addHTML( $text ) { $this->mBodytext .= $text; }
397 public function clearHTML() { $this->mBodytext = ''; }
398 public function getHTML() { return $this->mBodytext; }
399 public function debug( $text ) { $this->mDebugtext .= $text; }
401 /* @deprecated */
402 public function setParserOptions( $options ) {
403 wfDeprecated( __METHOD__ );
404 return $this->parserOptions( $options );
407 public function parserOptions( $options = null ) {
408 if ( !$this->mParserOptions ) {
409 $this->mParserOptions = new ParserOptions;
411 return wfSetVar( $this->mParserOptions, $options );
415 * Set the revision ID which will be seen by the wiki text parser
416 * for things such as embedded {{REVISIONID}} variable use.
417 * @param mixed $revid an integer, or NULL
418 * @return mixed previous value
420 public function setRevisionId( $revid ) {
421 $val = is_null( $revid ) ? null : intval( $revid );
422 return wfSetVar( $this->mRevisionId, $val );
426 * Convert wikitext to HTML and add it to the buffer
427 * Default assumes that the current page title will
428 * be used.
430 * @param string $text
431 * @param bool $linestart
433 public function addWikiText( $text, $linestart = true ) {
434 global $wgTitle;
435 $this->addWikiTextTitle($text, $wgTitle, $linestart);
438 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
439 $this->addWikiTextTitle($text, $title, $linestart);
442 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
443 $this->addWikiTextTitle( $text, $title, $linestart, true );
446 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
447 global $wgParser;
449 wfProfileIn( __METHOD__ );
451 wfIncrStats( 'pcache_not_possible' );
453 $popts = $this->parserOptions();
454 $oldTidy = $popts->setTidy( $tidy );
456 $parserOutput = $wgParser->parse( $text, $title, $popts,
457 $linestart, true, $this->mRevisionId );
459 $popts->setTidy( $oldTidy );
461 $this->addParserOutput( $parserOutput );
463 wfProfileOut( __METHOD__ );
467 * @todo document
468 * @param ParserOutput object &$parserOutput
470 public function addParserOutputNoText( &$parserOutput ) {
471 global $wgTitle, $wgExemptFromUserRobotsControl, $wgContentNamespaces;
473 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
474 $this->addCategoryLinks( $parserOutput->getCategories() );
475 $this->mNewSectionLink = $parserOutput->getNewSection();
477 if( is_null( $wgExemptFromUserRobotsControl ) ) {
478 $bannedNamespaces = $wgContentNamespaces;
479 } else {
480 $bannedNamespaces = $wgExemptFromUserRobotsControl;
482 if( !in_array( $wgTitle->getNamespace(), $bannedNamespaces ) ) {
483 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
484 # shouldn't
485 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
488 $this->addKeywords( $parserOutput );
489 $this->mParseWarnings = $parserOutput->getWarnings();
490 if ( $parserOutput->getCacheTime() == -1 ) {
491 $this->enableClientCache( false );
493 $this->mNoGallery = $parserOutput->getNoGallery();
494 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
495 // Versioning...
496 $this->mTemplateIds = wfArrayMerge( $this->mTemplateIds, (array)$parserOutput->mTemplateIds );
498 // Display title
499 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
500 $this->setPageTitle( $dt );
502 // Hooks registered in the object
503 global $wgParserOutputHooks;
504 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
505 list( $hookName, $data ) = $hookInfo;
506 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
507 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
511 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
515 * @todo document
516 * @param ParserOutput &$parserOutput
518 function addParserOutput( &$parserOutput ) {
519 $this->addParserOutputNoText( $parserOutput );
520 $text = $parserOutput->getText();
521 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
522 $this->addHTML( $text );
526 * Add wikitext to the buffer, assuming that this is the primary text for a page view
527 * Saves the text into the parser cache if possible.
529 * @param string $text
530 * @param Article $article
531 * @param bool $cache
532 * @deprecated Use Article::outputWikitext
534 public function addPrimaryWikiText( $text, $article, $cache = true ) {
535 global $wgParser, $wgUser;
537 wfDeprecated( __METHOD__ );
539 $popts = $this->parserOptions();
540 $popts->setTidy(true);
541 $parserOutput = $wgParser->parse( $text, $article->mTitle,
542 $popts, true, true, $this->mRevisionId );
543 $popts->setTidy(false);
544 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
545 $parserCache = ParserCache::singleton();
546 $parserCache->save( $parserOutput, $article, $wgUser );
549 $this->addParserOutput( $parserOutput );
553 * @deprecated use addWikiTextTidy()
555 public function addSecondaryWikiText( $text, $linestart = true ) {
556 global $wgTitle;
557 wfDeprecated( __METHOD__ );
558 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
562 * Add wikitext with tidy enabled
564 public function addWikiTextTidy( $text, $linestart = true ) {
565 global $wgTitle;
566 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
571 * Add the output of a QuickTemplate to the output buffer
573 * @param QuickTemplate $template
575 public function addTemplate( &$template ) {
576 ob_start();
577 $template->execute();
578 $this->addHTML( ob_get_contents() );
579 ob_end_clean();
583 * Parse wikitext and return the HTML.
585 * @param string $text
586 * @param bool $linestart Is this the start of a line?
587 * @param bool $interface ??
589 public function parse( $text, $linestart = true, $interface = false ) {
590 global $wgParser, $wgTitle;
591 $popts = $this->parserOptions();
592 if ( $interface) { $popts->setInterfaceMessage(true); }
593 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
594 $linestart, true, $this->mRevisionId );
595 if ( $interface) { $popts->setInterfaceMessage(false); }
596 return $parserOutput->getText();
600 * @param Article $article
601 * @param User $user
603 * @return bool True if successful, else false.
605 public function tryParserCache( &$article, $user ) {
606 $parserCache = ParserCache::singleton();
607 $parserOutput = $parserCache->get( $article, $user );
608 if ( $parserOutput !== false ) {
609 $this->addParserOutput( $parserOutput );
610 return true;
611 } else {
612 return false;
617 * @param int $maxage Maximum cache time on the Squid, in seconds.
619 public function setSquidMaxage( $maxage ) {
620 $this->mSquidMaxage = $maxage;
624 * Use enableClientCache(false) to force it to send nocache headers
625 * @param $state ??
627 public function enableClientCache( $state ) {
628 return wfSetVar( $this->mEnableClientCache, $state );
631 function getCacheVaryCookies() {
632 global $wgCookiePrefix, $wgCacheVaryCookies;
633 static $cookies;
634 if ( $cookies === null ) {
635 $cookies = array_merge(
636 array(
637 "{$wgCookiePrefix}Token",
638 "{$wgCookiePrefix}LoggedOut",
639 session_name()
641 $wgCacheVaryCookies
643 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
645 return $cookies;
648 function uncacheableBecauseRequestVars() {
649 global $wgRequest;
650 return $wgRequest->getText('useskin', false) === false
651 && $wgRequest->getText('uselang', false) === false;
655 * Check if the request has a cache-varying cookie header
656 * If it does, it's very important that we don't allow public caching
658 function haveCacheVaryCookies() {
659 global $wgRequest, $wgCookiePrefix;
660 $cookieHeader = $wgRequest->getHeader( 'cookie' );
661 if ( $cookieHeader === false ) {
662 return false;
664 $cvCookies = $this->getCacheVaryCookies();
665 foreach ( $cvCookies as $cookieName ) {
666 # Check for a simple string match, like the way squid does it
667 if ( strpos( $cookieHeader, $cookieName ) ) {
668 wfDebug( __METHOD__.": found $cookieName\n" );
669 return true;
672 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
673 return false;
676 /** Get a complete X-Vary-Options header */
677 public function getXVO() {
678 global $wgCookiePrefix;
679 $cvCookies = $this->getCacheVaryCookies();
680 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
681 $first = true;
682 foreach ( $cvCookies as $cookieName ) {
683 if ( $first ) {
684 $first = false;
685 } else {
686 $xvo .= ';';
688 $xvo .= 'string-contains=' . $cookieName;
690 return $xvo;
693 public function sendCacheControl() {
694 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
696 $response = $wgRequest->response();
697 if ($wgUseETag && $this->mETag)
698 $response->header("ETag: $this->mETag");
700 # don't serve compressed data to clients who can't handle it
701 # maintain different caches for logged-in users and non-logged in ones
702 $response->header( 'Vary: Accept-Encoding, Cookie' );
704 # Add an X-Vary-Options header for Squid with Wikimedia patches
705 $response->header( $this->getXVO() );
707 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
708 if( $wgUseSquid && session_id() == '' &&
709 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
711 if ( $wgUseESI ) {
712 # We'll purge the proxy cache explicitly, but require end user agents
713 # to revalidate against the proxy on each visit.
714 # Surrogate-Control controls our Squid, Cache-Control downstream caches
715 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
716 # start with a shorter timeout for initial testing
717 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
718 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
719 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
720 } else {
721 # We'll purge the proxy cache for anons explicitly, but require end user agents
722 # to revalidate against the proxy on each visit.
723 # IMPORTANT! The Squid needs to replace the Cache-Control header with
724 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
725 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
726 # start with a shorter timeout for initial testing
727 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
728 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
730 } else {
731 # We do want clients to cache if they can, but they *must* check for updates
732 # on revisiting the page.
733 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
734 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
735 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
737 if($this->mLastModified) $response->header( "Last-modified: {$this->mLastModified}" );
738 } else {
739 wfDebug( __METHOD__ . ": no caching **\n", false );
741 # In general, the absence of a last modified header should be enough to prevent
742 # the client from using its cache. We send a few other things just to make sure.
743 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
744 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
745 $response->header( 'Pragma: no-cache' );
750 * Finally, all the text has been munged and accumulated into
751 * the object, let's actually output it:
753 public function output() {
754 global $wgUser, $wgOutputEncoding, $wgRequest;
755 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
756 global $wgJsMimeType, $wgUseAjax, $wgAjaxSearch, $wgAjaxWatch;
757 global $wgEnableMWSuggest;
759 if( $this->mDoNothing ){
760 return;
763 wfProfileIn( __METHOD__ );
765 if ( '' != $this->mRedirect ) {
766 # Standards require redirect URLs to be absolute
767 $this->mRedirect = wfExpandUrl( $this->mRedirect );
768 if( $this->mRedirectCode == '301') {
769 if( !$wgDebugRedirects ) {
770 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
772 $this->mLastModified = wfTimestamp( TS_RFC2822 );
775 $this->sendCacheControl();
777 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
778 if( $wgDebugRedirects ) {
779 $url = htmlspecialchars( $this->mRedirect );
780 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
781 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
782 print "</body>\n</html>\n";
783 } else {
784 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
786 wfProfileOut( __METHOD__ );
787 return;
789 elseif ( $this->mStatusCode )
791 $statusMessage = array(
792 100 => 'Continue',
793 101 => 'Switching Protocols',
794 102 => 'Processing',
795 200 => 'OK',
796 201 => 'Created',
797 202 => 'Accepted',
798 203 => 'Non-Authoritative Information',
799 204 => 'No Content',
800 205 => 'Reset Content',
801 206 => 'Partial Content',
802 207 => 'Multi-Status',
803 300 => 'Multiple Choices',
804 301 => 'Moved Permanently',
805 302 => 'Found',
806 303 => 'See Other',
807 304 => 'Not Modified',
808 305 => 'Use Proxy',
809 307 => 'Temporary Redirect',
810 400 => 'Bad Request',
811 401 => 'Unauthorized',
812 402 => 'Payment Required',
813 403 => 'Forbidden',
814 404 => 'Not Found',
815 405 => 'Method Not Allowed',
816 406 => 'Not Acceptable',
817 407 => 'Proxy Authentication Required',
818 408 => 'Request Timeout',
819 409 => 'Conflict',
820 410 => 'Gone',
821 411 => 'Length Required',
822 412 => 'Precondition Failed',
823 413 => 'Request Entity Too Large',
824 414 => 'Request-URI Too Large',
825 415 => 'Unsupported Media Type',
826 416 => 'Request Range Not Satisfiable',
827 417 => 'Expectation Failed',
828 422 => 'Unprocessable Entity',
829 423 => 'Locked',
830 424 => 'Failed Dependency',
831 500 => 'Internal Server Error',
832 501 => 'Not Implemented',
833 502 => 'Bad Gateway',
834 503 => 'Service Unavailable',
835 504 => 'Gateway Timeout',
836 505 => 'HTTP Version Not Supported',
837 507 => 'Insufficient Storage'
840 if ( $statusMessage[$this->mStatusCode] )
841 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
844 $sk = $wgUser->getSkin();
846 if ( $wgUseAjax ) {
847 $this->addScriptFile( 'ajax.js' );
849 wfRunHooks( 'AjaxAddScript', array( &$this ) );
851 if( $wgAjaxSearch && $wgUser->getBoolOption( 'ajaxsearch' ) ) {
852 $this->addScriptFile( 'ajaxsearch.js' );
853 $this->addScript( "<script type=\"{$wgJsMimeType}\">hookEvent(\"load\", sajax_onload);</script>\n" );
856 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
857 $this->addScriptFile( 'ajaxwatch.js' );
860 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
861 $this->addScriptFile( 'mwsuggest.js' );
865 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
866 $this->addScriptFile( 'rightclickedit.js' );
869 # Buffer output; final headers may depend on later processing
870 ob_start();
872 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
873 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
875 if ($this->mArticleBodyOnly) {
876 $this->out($this->mBodytext);
877 } else {
878 // Hook that allows last minute changes to the output page, e.g.
879 // adding of CSS or Javascript by extensions.
880 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
882 wfProfileIn( 'Output-skin' );
883 $sk->outputPage( $this );
884 wfProfileOut( 'Output-skin' );
887 $this->sendCacheControl();
888 ob_end_flush();
889 wfProfileOut( __METHOD__ );
893 * @todo document
894 * @param string $ins
896 public function out( $ins ) {
897 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
898 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
899 $outs = $ins;
900 } else {
901 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
902 if ( false === $outs ) { $outs = $ins; }
904 print $outs;
908 * @todo document
910 public static function setEncodings() {
911 global $wgInputEncoding, $wgOutputEncoding;
912 global $wgUser, $wgContLang;
914 $wgInputEncoding = strtolower( $wgInputEncoding );
916 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
917 $wgOutputEncoding = strtolower( $wgOutputEncoding );
918 return;
920 $wgOutputEncoding = $wgInputEncoding;
924 * Deprecated, use wfReportTime() instead.
925 * @return string
926 * @deprecated
928 public function reportTime() {
929 wfDeprecated( __METHOD__ );
930 $time = wfReportTime();
931 return $time;
935 * Produce a "user is blocked" page.
937 * @param bool $return Whether to have a "return to $wgTitle" message or not.
938 * @return nothing
940 function blockedPage( $return = true ) {
941 global $wgUser, $wgContLang, $wgTitle, $wgLang;
943 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
944 $this->setRobotPolicy( 'noindex,nofollow' );
945 $this->setArticleRelated( false );
947 $name = User::whoIs( $wgUser->blockedBy() );
948 $reason = $wgUser->blockedFor();
949 if( $reason == '' ) {
950 $reason = wfMsg( 'blockednoreason' );
952 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
953 $ip = wfGetIP();
955 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
957 $blockid = $wgUser->mBlock->mId;
959 $blockExpiry = $wgUser->mBlock->mExpiry;
960 if ( $blockExpiry == 'infinity' ) {
961 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
962 // Search for localization in 'ipboptions'
963 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
964 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
965 if ( strpos( $option, ":" ) === false )
966 continue;
967 list( $show, $value ) = explode( ":", $option );
968 if ( $value == 'infinite' || $value == 'indefinite' ) {
969 $blockExpiry = $show;
970 break;
973 } else {
974 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
977 if ( $wgUser->mBlock->mAuto ) {
978 $msg = 'autoblockedtext';
979 } else {
980 $msg = 'blockedtext';
983 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
984 * This could be a username, an ip range, or a single ip. */
985 $intended = $wgUser->mBlock->mAddress;
987 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
989 # Don't auto-return to special pages
990 if( $return ) {
991 $return = $wgTitle->getNamespace() > -1 ? $wgTitle : NULL;
992 $this->returnToMain( null, $return );
997 * Output a standard error page
999 * @param string $title Message key for page title
1000 * @param string $msg Message key for page text
1001 * @param array $params Message parameters
1003 public function showErrorPage( $title, $msg, $params = array() ) {
1004 global $wgTitle;
1005 if ( isset($wgTitle) ) {
1006 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
1008 $this->setPageTitle( wfMsg( $title ) );
1009 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1010 $this->setRobotPolicy( 'noindex,nofollow' );
1011 $this->setArticleRelated( false );
1012 $this->enableClientCache( false );
1013 $this->mRedirect = '';
1014 $this->mBodytext = '';
1016 array_unshift( $params, 'parse' );
1017 array_unshift( $params, $msg );
1018 $this->addHtml( call_user_func_array( 'wfMsgExt', $params ) );
1020 $this->returnToMain();
1024 * Output a standard permission error page
1026 * @param array $errors Error message keys
1028 public function showPermissionsErrorPage( $errors, $action = null )
1030 global $wgTitle;
1032 $this->mDebugtext .= 'Original title: ' .
1033 $wgTitle->getPrefixedText() . "\n";
1034 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1035 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1036 $this->setRobotPolicy( 'noindex,nofollow' );
1037 $this->setArticleRelated( false );
1038 $this->enableClientCache( false );
1039 $this->mRedirect = '';
1040 $this->mBodytext = '';
1041 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1044 /** @deprecated */
1045 public function errorpage( $title, $msg ) {
1046 wfDeprecated( __METHOD__ );
1047 throw new ErrorPageError( $title, $msg );
1051 * Display an error page indicating that a given version of MediaWiki is
1052 * required to use it
1054 * @param mixed $version The version of MediaWiki needed to use the page
1056 public function versionRequired( $version ) {
1057 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1058 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1059 $this->setRobotPolicy( 'noindex,nofollow' );
1060 $this->setArticleRelated( false );
1061 $this->mBodytext = '';
1063 $this->addWikiMsg( 'versionrequiredtext', $version );
1064 $this->returnToMain();
1068 * Display an error page noting that a given permission bit is required.
1070 * @param string $permission key required
1072 public function permissionRequired( $permission ) {
1073 global $wgUser;
1075 $this->setPageTitle( wfMsg( 'badaccess' ) );
1076 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1077 $this->setRobotPolicy( 'noindex,nofollow' );
1078 $this->setArticleRelated( false );
1079 $this->mBodytext = '';
1081 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1082 User::getGroupsWithPermission( $permission ) );
1083 if( $groups ) {
1084 $this->addWikiMsg( 'badaccess-groups',
1085 implode( ', ', $groups ),
1086 count( $groups) );
1087 } else {
1088 $this->addWikiMsg( 'badaccess-group0' );
1090 $this->returnToMain();
1094 * Use permissionRequired.
1095 * @deprecated
1097 public function sysopRequired() {
1098 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1102 * Use permissionRequired.
1103 * @deprecated
1105 public function developerRequired() {
1106 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1110 * Produce the stock "please login to use the wiki" page
1112 public function loginToUse() {
1113 global $wgUser, $wgTitle, $wgContLang;
1115 if( $wgUser->isLoggedIn() ) {
1116 $this->permissionRequired( 'read' );
1117 return;
1120 $skin = $wgUser->getSkin();
1122 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1123 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1124 $this->setRobotPolicy( 'noindex,nofollow' );
1125 $this->setArticleFlag( false );
1127 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1128 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1129 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1130 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1132 # Don't return to the main page if the user can't read it
1133 # otherwise we'll end up in a pointless loop
1134 $mainPage = Title::newMainPage();
1135 if( $mainPage->userCanRead() )
1136 $this->returnToMain( null, $mainPage );
1139 /** @deprecated */
1140 public function databaseError( $fname, $sql, $error, $errno ) {
1141 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1145 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1146 * @return string The wikitext error-messages, formatted into a list.
1148 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1149 if ($action == null) {
1150 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1151 } else {
1152 $action_desc = wfMsg( "right-$action" );
1153 $action_desc[0] = strtolower($action_desc[0]);
1154 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1157 if (count( $errors ) > 1) {
1158 $text .= '<ul class="permissions-errors">' . "\n";
1160 foreach( $errors as $error )
1162 $text .= '<li>';
1163 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1164 $text .= "</li>\n";
1166 $text .= '</ul>';
1167 } else {
1168 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1171 return $text;
1175 * Display a page stating that the Wiki is in read-only mode,
1176 * and optionally show the source of the page that the user
1177 * was trying to edit. Should only be called (for this
1178 * purpose) after wfReadOnly() has returned true.
1180 * For historical reasons, this function is _also_ used to
1181 * show the error message when a user tries to edit a page
1182 * they are not allowed to edit. (Unless it's because they're
1183 * blocked, then we show blockedPage() instead.) In this
1184 * case, the second parameter should be set to true and a list
1185 * of reasons supplied as the third parameter.
1187 * @todo Needs to be split into multiple functions.
1189 * @param string $source Source code to show (or null).
1190 * @param bool $protected Is this a permissions error?
1191 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1193 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1194 global $wgUser, $wgTitle;
1195 $skin = $wgUser->getSkin();
1197 $this->setRobotPolicy( 'noindex,nofollow' );
1198 $this->setArticleRelated( false );
1200 // If no reason is given, just supply a default "I can't let you do
1201 // that, Dave" message. Should only occur if called by legacy code.
1202 if ( $protected && empty($reasons) ) {
1203 $reasons[] = array( 'badaccess-group0' );
1206 if ( !empty($reasons) ) {
1207 // Permissions error
1208 if( $source ) {
1209 $this->setPageTitle( wfMsg( 'viewsource' ) );
1210 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1211 } else {
1212 $this->setPageTitle( wfMsg( 'badaccess' ) );
1214 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1215 } else {
1216 // Wiki is read only
1217 $this->setPageTitle( wfMsg( 'readonly' ) );
1218 $reason = wfReadOnlyReason();
1219 $this->addWikiMsg( 'readonlytext', $reason );
1222 // Show source, if supplied
1223 if( is_string( $source ) ) {
1224 $this->addWikiMsg( 'viewsourcetext' );
1225 $text = Xml::openElement( 'textarea',
1226 array( 'id' => 'wpTextbox1',
1227 'name' => 'wpTextbox1',
1228 'cols' => $wgUser->getOption( 'cols' ),
1229 'rows' => $wgUser->getOption( 'rows' ),
1230 'readonly' => 'readonly' ) );
1231 $text .= htmlspecialchars( $source );
1232 $text .= Xml::closeElement( 'textarea' );
1233 $this->addHTML( $text );
1235 // Show templates used by this article
1236 $skin = $wgUser->getSkin();
1237 $article = new Article( $wgTitle );
1238 $this->addHTML( "<div class='templatesUsed'>
1239 {$skin->formatTemplates( $article->getUsedTemplates() )}
1240 </div>
1241 " );
1244 # If the title doesn't exist, it's fairly pointless to print a return
1245 # link to it. After all, you just tried editing it and couldn't, so
1246 # what's there to do there?
1247 if( $wgTitle->exists() ) {
1248 $this->returnToMain( null, $wgTitle );
1252 /** @deprecated */
1253 public function fatalError( $message ) {
1254 wfDeprecated( __METHOD__ );
1255 throw new FatalError( $message );
1258 /** @deprecated */
1259 public function unexpectedValueError( $name, $val ) {
1260 wfDeprecated( __METHOD__ );
1261 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1264 /** @deprecated */
1265 public function fileCopyError( $old, $new ) {
1266 wfDeprecated( __METHOD__ );
1267 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1270 /** @deprecated */
1271 public function fileRenameError( $old, $new ) {
1272 wfDeprecated( __METHOD__ );
1273 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1276 /** @deprecated */
1277 public function fileDeleteError( $name ) {
1278 wfDeprecated( __METHOD__ );
1279 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1282 /** @deprecated */
1283 public function fileNotFoundError( $name ) {
1284 wfDeprecated( __METHOD__ );
1285 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1288 public function showFatalError( $message ) {
1289 $this->setPageTitle( wfMsg( "internalerror" ) );
1290 $this->setRobotPolicy( "noindex,nofollow" );
1291 $this->setArticleRelated( false );
1292 $this->enableClientCache( false );
1293 $this->mRedirect = '';
1294 $this->mBodytext = $message;
1297 public function showUnexpectedValueError( $name, $val ) {
1298 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1301 public function showFileCopyError( $old, $new ) {
1302 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1305 public function showFileRenameError( $old, $new ) {
1306 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1309 public function showFileDeleteError( $name ) {
1310 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1313 public function showFileNotFoundError( $name ) {
1314 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1318 * Add a "return to" link pointing to a specified title
1320 * @param Title $title Title to link
1322 public function addReturnTo( $title ) {
1323 global $wgUser;
1324 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1325 $this->addHtml( "<p>{$link}</p>\n" );
1329 * Add a "return to" link pointing to a specified title,
1330 * or the title indicated in the request, or else the main page
1332 * @param null $unused No longer used
1333 * @param Title $returnto Title to return to
1335 public function returnToMain( $unused = null, $returnto = NULL ) {
1336 global $wgRequest;
1338 if ( $returnto == NULL ) {
1339 $returnto = $wgRequest->getText( 'returnto' );
1342 if ( '' === $returnto ) {
1343 $returnto = Title::newMainPage();
1346 if ( is_object( $returnto ) ) {
1347 $titleObj = $returnto;
1348 } else {
1349 $titleObj = Title::newFromText( $returnto );
1351 if ( !is_object( $titleObj ) ) {
1352 $titleObj = Title::newMainPage();
1355 $this->addReturnTo( $titleObj );
1359 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1360 * and uses the first 10 of them for META keywords
1362 * @param ParserOutput &$parserOutput
1364 private function addKeywords( &$parserOutput ) {
1365 global $wgTitle;
1366 $this->addKeyword( $wgTitle->getPrefixedText() );
1367 $count = 1;
1368 $links2d =& $parserOutput->getLinks();
1369 if ( !is_array( $links2d ) ) {
1370 return;
1372 foreach ( $links2d as $dbkeys ) {
1373 foreach( $dbkeys as $dbkey => $unused ) {
1374 $this->addKeyword( $dbkey );
1375 if ( ++$count > 10 ) {
1376 break 2;
1383 * @return string The doctype, opening <html>, and head element.
1385 public function headElement() {
1386 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1387 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1388 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1390 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1391 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1392 } else {
1393 $ret = '';
1396 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1398 if ( '' == $this->getHTMLTitle() ) {
1399 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1402 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1403 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1404 foreach($wgXhtmlNamespaces as $tag => $ns) {
1405 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1407 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1408 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1409 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1411 $ret .= $this->getHeadLinks();
1412 global $wgStylePath;
1413 if( $this->isPrintable() ) {
1414 $media = '';
1415 } else {
1416 $media = "media='print'";
1418 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1419 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1421 $sk = $wgUser->getSkin();
1422 // Load order here is key
1423 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1424 $ret .= $this->mScripts;
1425 $ret .= $sk->getSiteStyles();
1426 foreach( $this->mExtStyles as $tag ) {
1427 $ret .= Xml::element( 'link', $tag ) . "\n";
1429 $ret .= $sk->getUserStyles();
1430 $ret .= $this->getHeadItems();
1432 if ($wgUseTrackbacks && $this->isArticleRelated())
1433 $ret .= $wgTitle->trackbackRDF();
1435 $ret .= "</head>\n";
1436 return $ret;
1439 protected function addDefaultMeta() {
1440 global $wgVersion;
1441 $this->addMeta( "generator", "MediaWiki $wgVersion" );
1443 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1444 if( $p !== 'index,follow' ) {
1445 // http://www.robotstxt.org/wc/meta-user.html
1446 // Only show if it's different from the default robots policy
1447 $this->addMeta( 'robots', $p );
1450 if ( count( $this->mKeywords ) > 0 ) {
1451 $strip = array(
1452 "/<.*?>/" => '',
1453 "/_/" => ' '
1455 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1460 * @return string HTML tag links to be put in the header.
1462 public function getHeadLinks() {
1463 global $wgRequest, $wgFeed;
1465 // Ideally this should happen earlier, somewhere. :P
1466 $this->addDefaultMeta();
1468 $tags = array();
1470 foreach ( $this->mMetatags as $tag ) {
1471 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1472 $a = 'http-equiv';
1473 $tag[0] = substr( $tag[0], 5 );
1474 } else {
1475 $a = 'name';
1477 $tags[] = Xml::element( 'meta',
1478 array(
1479 $a => $tag[0],
1480 'content' => $tag[1] ) );
1482 foreach ( $this->mLinktags as $tag ) {
1483 $tags[] = Xml::element( 'link', $tag );
1486 if( $wgFeed ) {
1487 global $wgTitle;
1488 foreach( $this->getSyndicationLinks() as $format => $link ) {
1489 # Use the page name for the title (accessed through $wgTitle since
1490 # there's no other way). In principle, this could lead to issues
1491 # with having the same name for different feeds corresponding to
1492 # the same page, but we can't avoid that at this low a level.
1494 $tags[] = $this->feedLink(
1495 $format,
1496 $link,
1497 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1500 # Recent changes feed should appear on every page (except recentchanges,
1501 # that would be redundant). Put it after the per-page feed to avoid
1502 # changing existing behavior. It's still available, probably via a
1503 # menu in your browser. Some sites might have a different feed they'd
1504 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1505 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1506 # If so, use it instead.
1508 global $wgOverrideSiteFeed, $wgSitename;
1509 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1511 if ( $wgOverrideSiteFeed ) {
1512 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1513 $tags[] = $this->feedLink (
1514 $type,
1515 htmlspecialchars( $feedUrl ),
1516 wfMsg( "site-{$type}-feed", $wgSitename ) );
1519 else if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1520 $tags[] = $this->feedLink(
1521 'rss',
1522 $rctitle->getFullURL( 'feed=rss' ),
1523 wfMsg( 'site-rss-feed', $wgSitename ) );
1524 $tags[] = $this->feedLink(
1525 'atom',
1526 $rctitle->getFullURL( 'feed=atom' ),
1527 wfMsg( 'site-atom-feed', $wgSitename ) );
1531 return implode( "\n\t\t", $tags ) . "\n";
1535 * Return URLs for each supported syndication format for this page.
1536 * @return array associating format keys with URLs
1538 public function getSyndicationLinks() {
1539 global $wgTitle, $wgFeedClasses;
1540 $links = array();
1542 if( $this->isSyndicated() ) {
1543 if( is_string( $this->getFeedAppendQuery() ) ) {
1544 $appendQuery = "&" . $this->getFeedAppendQuery();
1545 } else {
1546 $appendQuery = "";
1549 foreach( $wgFeedClasses as $format => $class ) {
1550 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1553 return $links;
1557 * Generate a <link rel/> for an RSS feed.
1559 private function feedLink( $type, $url, $text ) {
1560 return Xml::element( 'link', array(
1561 'rel' => 'alternate',
1562 'type' => "application/$type+xml",
1563 'title' => $text,
1564 'href' => $url ) );
1568 * Turn off regular page output and return an error reponse
1569 * for when rate limiting has triggered.
1571 public function rateLimited() {
1572 global $wgTitle;
1574 $this->setPageTitle(wfMsg('actionthrottled'));
1575 $this->setRobotPolicy( 'noindex,follow' );
1576 $this->setArticleRelated( false );
1577 $this->enableClientCache( false );
1578 $this->mRedirect = '';
1579 $this->clearHTML();
1580 $this->setStatusCode(503);
1581 $this->addWikiMsg( 'actionthrottledtext' );
1583 $this->returnToMain( null, $wgTitle );
1587 * Show an "add new section" link?
1589 * @return bool
1591 public function showNewSectionLink() {
1592 return $this->mNewSectionLink;
1596 * Show a warning about slave lag
1598 * If the lag is higher than $wgSlaveLagCritical seconds,
1599 * then the warning is a bit more obvious. If the lag is
1600 * lower than $wgSlaveLagWarning, then no warning is shown.
1602 * @param int $lag Slave lag
1604 public function showLagWarning( $lag ) {
1605 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1606 if( $lag >= $wgSlaveLagWarning ) {
1607 $message = $lag < $wgSlaveLagCritical
1608 ? 'lag-warn-normal'
1609 : 'lag-warn-high';
1610 $warning = wfMsgExt( $message, 'parse', $lag );
1611 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1616 * Add a wikitext-formatted message to the output.
1617 * This is equivalent to:
1619 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1621 public function addWikiMsg( /*...*/ ) {
1622 $args = func_get_args();
1623 $name = array_shift( $args );
1624 $this->addWikiMsgArray( $name, $args );
1628 * Add a wikitext-formatted message to the output.
1629 * Like addWikiMsg() except the parameters are taken as an array
1630 * instead of a variable argument list.
1632 * $options is passed through to wfMsgExt(), see that function for details.
1634 public function addWikiMsgArray( $name, $args, $options = array() ) {
1635 $options[] = 'parse';
1636 $text = wfMsgExt( $name, $options, $args );
1637 $this->addHTML( $text );
1641 * This function takes a number of message/argument specifications, wraps them in
1642 * some overall structure, and then parses the result and adds it to the output.
1644 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1645 * on. The subsequent arguments may either be strings, in which case they are the
1646 * message names, or an arrays, in which case the first element is the message name,
1647 * and subsequent elements are the parameters to that message.
1649 * The special named parameter 'options' in a message specification array is passed
1650 * through to the $options parameter of wfMsgExt().
1652 * Don't use this for messages that are not in users interface language.
1654 * For example:
1656 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1658 * Is equivalent to:
1660 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1662 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1663 $msgSpecs = func_get_args();
1664 array_shift( $msgSpecs );
1665 $msgSpecs = array_values( $msgSpecs );
1666 $s = $wrap;
1667 foreach ( $msgSpecs as $n => $spec ) {
1668 $options = array();
1669 if ( is_array( $spec ) ) {
1670 $args = $spec;
1671 $name = array_shift( $args );
1672 if ( isset( $args['options'] ) ) {
1673 $options = $args['options'];
1674 unset( $args['options'] );
1676 } else {
1677 $args = array();
1678 $name = $spec;
1680 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1682 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );