Vary the cache on session, Token and LoggedOut cookies, but not UserID cookie. The...
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
4 /**
5 */
6
7 /**
8 * @todo document
9 */
10 class OutputPage {
11 var $mMetatags, $mKeywords;
12 var $mLinktags, $mPagetitle, $mBodytext, $mDebugtext;
13 var $mHTMLtitle, $mRobotpolicy, $mIsarticle, $mPrintable;
14 var $mSubtitle, $mRedirect, $mStatusCode;
15 var $mLastModified, $mETag, $mCategoryLinks;
16 var $mScripts, $mLinkColours, $mPageLinkTitle;
17
18 var $mAllowUserJs;
19 var $mSuppressQuickbar;
20 var $mOnloadHandler;
21 var $mDoNothing;
22 var $mContainsOldMagic, $mContainsNewMagic;
23 var $mIsArticleRelated;
24 protected $mParserOptions; // lazy initialised, use parserOptions()
25 var $mShowFeedLinks = false;
26 var $mFeedLinksAppendQuery = false;
27 var $mEnableClientCache = true;
28 var $mArticleBodyOnly = false;
29
30 var $mNewSectionLink = false;
31 var $mNoGallery = false;
32 var $mPageTitleActionText = '';
33 var $mParseWarnings = array();
34
35 /**
36 * Constructor
37 * Initialise private variables
38 */
39 function __construct() {
40 global $wgAllowUserJs;
41 $this->mAllowUserJs = $wgAllowUserJs;
42 $this->mMetatags = $this->mKeywords = $this->mLinktags = array();
43 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
44 $this->mRedirect = $this->mLastModified =
45 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
46 $this->mOnloadHandler = $this->mPageLinkTitle = '';
47 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
48 $this->mSuppressQuickbar = $this->mPrintable = false;
49 $this->mLanguageLinks = array();
50 $this->mCategoryLinks = array();
51 $this->mDoNothing = false;
52 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
53 $this->mParserOptions = null;
54 $this->mSquidMaxage = 0;
55 $this->mScripts = '';
56 $this->mHeadItems = array();
57 $this->mETag = false;
58 $this->mRevisionId = null;
59 $this->mNewSectionLink = false;
60 $this->mTemplateIds = array();
61 }
62
63 public function redirect( $url, $responsecode = '302' ) {
64 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
65 $this->mRedirect = str_replace( "\n", '', $url );
66 $this->mRedirectCode = $responsecode;
67 }
68
69 public function getRedirect() {
70 return $this->mRedirect;
71 }
72
73 /**
74 * Set the HTTP status code to send with the output.
75 *
76 * @param int $statusCode
77 * @return nothing
78 */
79 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
80
81 # To add an http-equiv meta tag, precede the name with "http:"
82 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
83 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
84 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
85 function addStyle( $style ) {
86 global $wgStylePath, $wgStyleVersion;
87 $this->addLink(
88 array(
89 'rel' => 'stylesheet',
90 'href' => $wgStylePath . '/' . $style . '?' . $wgStyleVersion ) );
91 }
92
93 /**
94 * Add a self-contained script tag with the given contents
95 * @param string $script JavaScript text, no <script> tags
96 */
97 function addInlineScript( $script ) {
98 global $wgJsMimeType;
99 $this->mScripts .= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
100 }
101
102 function getScript() {
103 return $this->mScripts . $this->getHeadItems();
104 }
105
106 function getHeadItems() {
107 $s = '';
108 foreach ( $this->mHeadItems as $item ) {
109 $s .= $item;
110 }
111 return $s;
112 }
113
114 function addHeadItem( $name, $value ) {
115 $this->mHeadItems[$name] = $value;
116 }
117
118 function hasHeadItem( $name ) {
119 return isset( $this->mHeadItems[$name] );
120 }
121
122 function setETag($tag) { $this->mETag = $tag; }
123 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
124 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
125
126 function addLink( $linkarr ) {
127 # $linkarr should be an associative array of attributes. We'll escape on output.
128 array_push( $this->mLinktags, $linkarr );
129 }
130
131 function addMetadataLink( $linkarr ) {
132 # note: buggy CC software only reads first "meta" link
133 static $haveMeta = false;
134 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
135 $this->addLink( $linkarr );
136 $haveMeta = true;
137 }
138
139 /**
140 * checkLastModified tells the client to use the client-cached page if
141 * possible. If sucessful, the OutputPage is disabled so that
142 * any future call to OutputPage->output() have no effect.
143 *
144 * @return bool True iff cache-ok headers was sent.
145 */
146 function checkLastModified ( $timestamp ) {
147 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
148 $fname = 'OutputPage::checkLastModified';
149
150 if ( !$timestamp || $timestamp == '19700101000000' ) {
151 wfDebug( "$fname: CACHE DISABLED, NO TIMESTAMP\n" );
152 return;
153 }
154 if( !$wgCachePages ) {
155 wfDebug( "$fname: CACHE DISABLED\n", false );
156 return;
157 }
158 if( $wgUser->getOption( 'nocache' ) ) {
159 wfDebug( "$fname: USER DISABLED CACHE\n", false );
160 return;
161 }
162
163 $timestamp=wfTimestamp(TS_MW,$timestamp);
164 $lastmod = wfTimestamp( TS_RFC2822, max( $timestamp, $wgUser->mTouched, $wgCacheEpoch ) );
165
166 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
167 # IE sends sizes after the date like this:
168 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
169 # this breaks strtotime().
170 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
171
172 wfSuppressWarnings(); // E_STRICT system time bitching
173 $modsinceTime = strtotime( $modsince );
174 wfRestoreWarnings();
175
176 $ismodsince = wfTimestamp( TS_MW, $modsinceTime ? $modsinceTime : 1 );
177 wfDebug( "$fname: -- client send If-Modified-Since: " . $modsince . "\n", false );
178 wfDebug( "$fname: -- we might send Last-Modified : $lastmod\n", false );
179 if( ($ismodsince >= $timestamp ) && $wgUser->validateCache( $ismodsince ) && $ismodsince >= $wgCacheEpoch ) {
180 # Make sure you're in a place you can leave when you call us!
181 $wgRequest->response()->header( "HTTP/1.0 304 Not Modified" );
182 $this->mLastModified = $lastmod;
183 $this->sendCacheControl();
184 wfDebug( "$fname: CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
185 $this->disable();
186
187 // Don't output a compressed blob when using ob_gzhandler;
188 // it's technically against HTTP spec and seems to confuse
189 // Firefox when the response gets split over two packets.
190 wfClearOutputBuffers();
191
192 return true;
193 } else {
194 wfDebug( "$fname: READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
195 $this->mLastModified = $lastmod;
196 }
197 } else {
198 wfDebug( "$fname: client did not send If-Modified-Since header\n", false );
199 $this->mLastModified = $lastmod;
200 }
201 }
202
203 function setPageTitleActionText( $text ) {
204 $this->mPageTitleActionText = $text;
205 }
206
207 function getPageTitleActionText () {
208 if ( isset( $this->mPageTitleActionText ) ) {
209 return $this->mPageTitleActionText;
210 }
211 }
212
213 public function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
214 public function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
215 public function setPageTitle( $name ) {
216 global $action, $wgContLang;
217 $name = $wgContLang->convert($name, true);
218 $this->mPagetitle = $name;
219 if(!empty($action)) {
220 $taction = $this->getPageTitleActionText();
221 if( !empty( $taction ) ) {
222 $name .= ' - '.$taction;
223 }
224 }
225
226 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
227 }
228 public function getHTMLTitle() { return $this->mHTMLtitle; }
229 public function getPageTitle() { return $this->mPagetitle; }
230 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
231 public function getSubtitle() { return $this->mSubtitle; }
232 public function isArticle() { return $this->mIsarticle; }
233 public function setPrintable() { $this->mPrintable = true; }
234 public function isPrintable() { return $this->mPrintable; }
235 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
236 public function isSyndicated() { return $this->mShowFeedLinks; }
237 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
238 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
239 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
240 public function getOnloadHandler() { return $this->mOnloadHandler; }
241 public function disable() { $this->mDoNothing = true; }
242
243 public function setArticleRelated( $v ) {
244 $this->mIsArticleRelated = $v;
245 if ( !$v ) {
246 $this->mIsarticle = false;
247 }
248 }
249 public function setArticleFlag( $v ) {
250 $this->mIsarticle = $v;
251 if ( $v ) {
252 $this->mIsArticleRelated = $v;
253 }
254 }
255
256 public function isArticleRelated() { return $this->mIsArticleRelated; }
257
258 public function getLanguageLinks() { return $this->mLanguageLinks; }
259 public function addLanguageLinks($newLinkArray) {
260 $this->mLanguageLinks += $newLinkArray;
261 }
262 public function setLanguageLinks($newLinkArray) {
263 $this->mLanguageLinks = $newLinkArray;
264 }
265
266 public function getCategoryLinks() {
267 return $this->mCategoryLinks;
268 }
269
270 /**
271 * Add an array of categories, with names in the keys
272 */
273 public function addCategoryLinks($categories) {
274 global $wgUser, $wgContLang;
275
276 if ( !is_array( $categories ) ) {
277 return;
278 }
279 # Add the links to the link cache in a batch
280 $arr = array( NS_CATEGORY => $categories );
281 $lb = new LinkBatch;
282 $lb->setArray( $arr );
283 $lb->execute();
284
285 $sk = $wgUser->getSkin();
286 foreach ( $categories as $category => $unused ) {
287 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
288 $text = $wgContLang->convertHtml( $title->getText() );
289 $this->mCategoryLinks[] = $sk->makeLinkObj( $title, $text );
290 }
291 }
292
293 public function setCategoryLinks($categories) {
294 $this->mCategoryLinks = array();
295 $this->addCategoryLinks($categories);
296 }
297
298 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
299 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
300
301 public function disallowUserJs() { $this->mAllowUserJs = false; }
302 public function isUserJsAllowed() { return $this->mAllowUserJs; }
303
304 public function addHTML( $text ) { $this->mBodytext .= $text; }
305 public function clearHTML() { $this->mBodytext = ''; }
306 public function getHTML() { return $this->mBodytext; }
307 public function debug( $text ) { $this->mDebugtext .= $text; }
308
309 /* @deprecated */
310 public function setParserOptions( $options ) {
311 return $this->parserOptions( $options );
312 }
313
314 public function parserOptions( $options = null ) {
315 if ( !$this->mParserOptions ) {
316 $this->mParserOptions = new ParserOptions;
317 }
318 return wfSetVar( $this->mParserOptions, $options );
319 }
320
321 /**
322 * Set the revision ID which will be seen by the wiki text parser
323 * for things such as embedded {{REVISIONID}} variable use.
324 * @param mixed $revid an integer, or NULL
325 * @return mixed previous value
326 */
327 public function setRevisionId( $revid ) {
328 $val = is_null( $revid ) ? null : intval( $revid );
329 return wfSetVar( $this->mRevisionId, $val );
330 }
331
332 /**
333 * Convert wikitext to HTML and add it to the buffer
334 * Default assumes that the current page title will
335 * be used.
336 *
337 * @param string $text
338 * @param bool $linestart
339 */
340 public function addWikiText( $text, $linestart = true ) {
341 global $wgTitle;
342 $this->addWikiTextTitle($text, $wgTitle, $linestart);
343 }
344
345 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
346 $this->addWikiTextTitle($text, $title, $linestart);
347 }
348
349 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
350 $this->addWikiTextTitle( $text, $title, $linestart, true );
351 }
352
353 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
354 global $wgParser;
355
356 $fname = 'OutputPage:addWikiTextTitle';
357 wfProfileIn($fname);
358
359 wfIncrStats('pcache_not_possible');
360
361 $popts = $this->parserOptions();
362 $oldTidy = $popts->setTidy($tidy);
363
364 $parserOutput = $wgParser->parse( $text, $title, $popts,
365 $linestart, true, $this->mRevisionId );
366
367 $popts->setTidy( $oldTidy );
368
369 $this->addParserOutput( $parserOutput );
370
371 wfProfileOut($fname);
372 }
373
374 /**
375 * @todo document
376 * @param ParserOutput object &$parserOutput
377 */
378 public function addParserOutputNoText( &$parserOutput ) {
379 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
380 $this->addCategoryLinks( $parserOutput->getCategories() );
381 $this->mNewSectionLink = $parserOutput->getNewSection();
382 $this->addKeywords( $parserOutput );
383 $this->mParseWarnings = $parserOutput->getWarnings();
384 if ( $parserOutput->getCacheTime() == -1 ) {
385 $this->enableClientCache( false );
386 }
387 $this->mNoGallery = $parserOutput->getNoGallery();
388 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
389 // Versioning...
390 $this->mTemplateIds += (array)$parserOutput->mTemplateIds;
391
392 # Display title
393 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
394 $this->setPageTitle( $dt );
395
396 # Hooks registered in the object
397 global $wgParserOutputHooks;
398 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
399 list( $hookName, $data ) = $hookInfo;
400 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
401 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
402 }
403 }
404
405 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
406 }
407
408 /**
409 * @todo document
410 * @param ParserOutput &$parserOutput
411 */
412 function addParserOutput( &$parserOutput ) {
413 $this->addParserOutputNoText( $parserOutput );
414 $text = $parserOutput->getText();
415 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
416 $this->addHTML( $text );
417 }
418
419 /**
420 * Add wikitext to the buffer, assuming that this is the primary text for a page view
421 * Saves the text into the parser cache if possible.
422 *
423 * @param string $text
424 * @param Article $article
425 * @param bool $cache
426 * @deprecated Use Article::outputWikitext
427 */
428 public function addPrimaryWikiText( $text, $article, $cache = true ) {
429 global $wgParser, $wgUser;
430
431 $popts = $this->parserOptions();
432 $popts->setTidy(true);
433 $parserOutput = $wgParser->parse( $text, $article->mTitle,
434 $popts, true, true, $this->mRevisionId );
435 $popts->setTidy(false);
436 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
437 $parserCache =& ParserCache::singleton();
438 $parserCache->save( $parserOutput, $article, $wgUser );
439 }
440
441 $this->addParserOutput( $parserOutput );
442 }
443
444 /**
445 * @deprecated use addWikiTextTidy()
446 */
447 public function addSecondaryWikiText( $text, $linestart = true ) {
448 global $wgTitle;
449 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
450 }
451
452 /**
453 * Add wikitext with tidy enabled
454 */
455 public function addWikiTextTidy( $text, $linestart = true ) {
456 global $wgTitle;
457 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
458 }
459
460
461 /**
462 * Add the output of a QuickTemplate to the output buffer
463 *
464 * @param QuickTemplate $template
465 */
466 public function addTemplate( &$template ) {
467 ob_start();
468 $template->execute();
469 $this->addHTML( ob_get_contents() );
470 ob_end_clean();
471 }
472
473 /**
474 * Parse wikitext and return the HTML.
475 *
476 * @param string $text
477 * @param bool $linestart Is this the start of a line?
478 * @param bool $interface ??
479 */
480 public function parse( $text, $linestart = true, $interface = false ) {
481 global $wgParser, $wgTitle;
482 $popts = $this->parserOptions();
483 if ( $interface) { $popts->setInterfaceMessage(true); }
484 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
485 $linestart, true, $this->mRevisionId );
486 if ( $interface) { $popts->setInterfaceMessage(false); }
487 return $parserOutput->getText();
488 }
489
490 /**
491 * @param Article $article
492 * @param User $user
493 *
494 * @return bool True if successful, else false.
495 */
496 public function tryParserCache( &$article, $user ) {
497 $parserCache =& ParserCache::singleton();
498 $parserOutput = $parserCache->get( $article, $user );
499 if ( $parserOutput !== false ) {
500 $this->addParserOutput( $parserOutput );
501 return true;
502 } else {
503 return false;
504 }
505 }
506
507 /**
508 * @param int $maxage Maximum cache time on the Squid, in seconds.
509 */
510 public function setSquidMaxage( $maxage ) {
511 $this->mSquidMaxage = $maxage;
512 }
513
514 /**
515 * Use enableClientCache(false) to force it to send nocache headers
516 * @param $state ??
517 */
518 public function enableClientCache( $state ) {
519 return wfSetVar( $this->mEnableClientCache, $state );
520 }
521
522 function getCacheVaryCookies() {
523 global $wgCookiePrefix;
524 return array(
525 "{$wgCookiePrefix}Token",
526 "{$wgCookiePrefix}LoggedOut",
527 session_name() );
528 }
529
530 function uncacheableBecauseRequestVars() {
531 global $wgRequest;
532 return $wgRequest->getText('useskin', false) === false
533 && $wgRequest->getText('uselang', false) === false;
534 }
535
536 /**
537 * Check if the request has a cache-varying cookie header
538 * If it does, it's very important that we don't allow public caching
539 */
540 function haveCacheVaryCookies() {
541 global $wgRequest, $wgCookiePrefix;
542 $cookieHeader = $wgRequest->getHeader( 'cookie' );
543 if ( $cookieHeader === false ) {
544 return false;
545 }
546 $cvCookies = $this->getCacheVaryCookies();
547 foreach ( $cvCookies as $cookieName ) {
548 # Check for a simple string match, like the way squid does it
549 if ( strpos( $cookieHeader, $cookieName ) ) {
550 wfDebug( __METHOD__.": found $cookieName\n" );
551 return true;
552 }
553 }
554 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
555 return false;
556 }
557
558 /** Get a complete X-Vary-Options header */
559 public function getXVO() {
560 global $wgCookiePrefix;
561 $cvCookies = $this->getCacheVaryCookies();
562 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
563 foreach ( $cvCookies as $cookieName ) {
564 $xvo .= 'string-contains=' . $cookieName;
565 }
566 return $xvo;
567 }
568
569 public function sendCacheControl() {
570 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
571 $fname = 'OutputPage::sendCacheControl';
572
573 $response = $wgRequest->response();
574 if ($wgUseETag && $this->mETag)
575 $response->header("ETag: $this->mETag");
576
577 # don't serve compressed data to clients who can't handle it
578 # maintain different caches for logged-in users and non-logged in ones
579 $response->header( 'Vary: Accept-Encoding, Cookie' );
580
581 # Add an X-Vary-Options header for Squid with Wikimedia patches
582 $response->header( $this->getXVO() );
583
584 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
585 if( $wgUseSquid && session_id() == '' &&
586 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
587 {
588 if ( $wgUseESI ) {
589 # We'll purge the proxy cache explicitly, but require end user agents
590 # to revalidate against the proxy on each visit.
591 # Surrogate-Control controls our Squid, Cache-Control downstream caches
592 wfDebug( "$fname: proxy caching with ESI; {$this->mLastModified} **\n", false );
593 # start with a shorter timeout for initial testing
594 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
595 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
596 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
597 } else {
598 # We'll purge the proxy cache for anons explicitly, but require end user agents
599 # to revalidate against the proxy on each visit.
600 # IMPORTANT! The Squid needs to replace the Cache-Control header with
601 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
602 wfDebug( "$fname: local proxy caching; {$this->mLastModified} **\n", false );
603 # start with a shorter timeout for initial testing
604 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
605 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
606 }
607 } else {
608 # We do want clients to cache if they can, but they *must* check for updates
609 # on revisiting the page.
610 wfDebug( "$fname: private caching; {$this->mLastModified} **\n", false );
611 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
612 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
613 }
614 if($this->mLastModified) $response->header( "Last-modified: {$this->mLastModified}" );
615 } else {
616 wfDebug( "$fname: no caching **\n", false );
617
618 # In general, the absence of a last modified header should be enough to prevent
619 # the client from using its cache. We send a few other things just to make sure.
620 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
621 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
622 $response->header( 'Pragma: no-cache' );
623 }
624 }
625
626 /**
627 * Finally, all the text has been munged and accumulated into
628 * the object, let's actually output it:
629 */
630 public function output() {
631 global $wgUser, $wgOutputEncoding, $wgRequest;
632 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
633 global $wgJsMimeType, $wgStylePath, $wgUseAjax, $wgAjaxSearch, $wgAjaxWatch;
634 global $wgServer, $wgStyleVersion;
635
636 if( $this->mDoNothing ){
637 return;
638 }
639 $fname = 'OutputPage::output';
640 wfProfileIn( $fname );
641
642 if ( '' != $this->mRedirect ) {
643 # Standards require redirect URLs to be absolute
644 $this->mRedirect = wfExpandUrl( $this->mRedirect );
645 if( $this->mRedirectCode == '301') {
646 if( !$wgDebugRedirects ) {
647 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
648 }
649 $this->mLastModified = wfTimestamp( TS_RFC2822 );
650 }
651
652 $this->sendCacheControl();
653
654 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
655 if( $wgDebugRedirects ) {
656 $url = htmlspecialchars( $this->mRedirect );
657 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
658 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
659 print "</body>\n</html>\n";
660 } else {
661 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
662 }
663 wfProfileOut( $fname );
664 return;
665 }
666 elseif ( $this->mStatusCode )
667 {
668 $statusMessage = array(
669 100 => 'Continue',
670 101 => 'Switching Protocols',
671 102 => 'Processing',
672 200 => 'OK',
673 201 => 'Created',
674 202 => 'Accepted',
675 203 => 'Non-Authoritative Information',
676 204 => 'No Content',
677 205 => 'Reset Content',
678 206 => 'Partial Content',
679 207 => 'Multi-Status',
680 300 => 'Multiple Choices',
681 301 => 'Moved Permanently',
682 302 => 'Found',
683 303 => 'See Other',
684 304 => 'Not Modified',
685 305 => 'Use Proxy',
686 307 => 'Temporary Redirect',
687 400 => 'Bad Request',
688 401 => 'Unauthorized',
689 402 => 'Payment Required',
690 403 => 'Forbidden',
691 404 => 'Not Found',
692 405 => 'Method Not Allowed',
693 406 => 'Not Acceptable',
694 407 => 'Proxy Authentication Required',
695 408 => 'Request Timeout',
696 409 => 'Conflict',
697 410 => 'Gone',
698 411 => 'Length Required',
699 412 => 'Precondition Failed',
700 413 => 'Request Entity Too Large',
701 414 => 'Request-URI Too Large',
702 415 => 'Unsupported Media Type',
703 416 => 'Request Range Not Satisfiable',
704 417 => 'Expectation Failed',
705 422 => 'Unprocessable Entity',
706 423 => 'Locked',
707 424 => 'Failed Dependency',
708 500 => 'Internal Server Error',
709 501 => 'Not Implemented',
710 502 => 'Bad Gateway',
711 503 => 'Service Unavailable',
712 504 => 'Gateway Timeout',
713 505 => 'HTTP Version Not Supported',
714 507 => 'Insufficient Storage'
715 );
716
717 if ( $statusMessage[$this->mStatusCode] )
718 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
719 }
720
721 $sk = $wgUser->getSkin();
722
723 if ( $wgUseAjax ) {
724 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajax.js?$wgStyleVersion\"></script>\n" );
725
726 wfRunHooks( 'AjaxAddScript', array( &$this ) );
727
728 if( $wgAjaxSearch && $wgUser->getBoolOption( 'ajaxsearch' ) ) {
729 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxsearch.js?$wgStyleVersion\"></script>\n" );
730 $this->addScript( "<script type=\"{$wgJsMimeType}\">hookEvent(\"load\", sajax_onload);</script>\n" );
731 }
732
733 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
734 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxwatch.js?$wgStyleVersion\"></script>\n" );
735 }
736 }
737
738
739
740 # Buffer output; final headers may depend on later processing
741 ob_start();
742
743 # Disable temporary placeholders, so that the skin produces HTML
744 $sk->postParseLinkColour( false );
745
746 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
747 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
748
749 if ($this->mArticleBodyOnly) {
750 $this->out($this->mBodytext);
751 } else {
752 wfProfileIn( 'Output-skin' );
753 $sk->outputPage( $this );
754 wfProfileOut( 'Output-skin' );
755 }
756
757 $this->sendCacheControl();
758 ob_end_flush();
759 wfProfileOut( $fname );
760 }
761
762 /**
763 * @todo document
764 * @param string $ins
765 */
766 public function out( $ins ) {
767 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
768 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
769 $outs = $ins;
770 } else {
771 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
772 if ( false === $outs ) { $outs = $ins; }
773 }
774 print $outs;
775 }
776
777 /**
778 * @todo document
779 */
780 public static function setEncodings() {
781 global $wgInputEncoding, $wgOutputEncoding;
782 global $wgUser, $wgContLang;
783
784 $wgInputEncoding = strtolower( $wgInputEncoding );
785
786 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
787 $wgOutputEncoding = strtolower( $wgOutputEncoding );
788 return;
789 }
790 $wgOutputEncoding = $wgInputEncoding;
791 }
792
793 /**
794 * Deprecated, use wfReportTime() instead.
795 * @return string
796 * @deprecated
797 */
798 public function reportTime() {
799 $time = wfReportTime();
800 return $time;
801 }
802
803 /**
804 * Produce a "user is blocked" page.
805 *
806 * @param bool $return Whether to have a "return to $wgTitle" message or not.
807 * @return nothing
808 */
809 function blockedPage( $return = true ) {
810 global $wgUser, $wgContLang, $wgTitle, $wgLang;
811
812 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
813 $this->setRobotpolicy( 'noindex,nofollow' );
814 $this->setArticleRelated( false );
815
816 $name = User::whoIs( $wgUser->blockedBy() );
817 $reason = $wgUser->blockedFor();
818 if( $reason == '' ) {
819 $reason = wfMsg( 'blockednoreason' );
820 }
821 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
822 $ip = wfGetIP();
823
824 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
825
826 $blockid = $wgUser->mBlock->mId;
827
828 $blockExpiry = $wgUser->mBlock->mExpiry;
829 if ( $blockExpiry == 'infinity' ) {
830 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
831 // Search for localization in 'ipboptions'
832 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
833 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
834 if ( strpos( $option, ":" ) === false )
835 continue;
836 list( $show, $value ) = explode( ":", $option );
837 if ( $value == 'infinite' || $value == 'indefinite' ) {
838 $blockExpiry = $show;
839 break;
840 }
841 }
842 } else {
843 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
844 }
845
846 if ( $wgUser->mBlock->mAuto ) {
847 $msg = 'autoblockedtext';
848 } else {
849 $msg = 'blockedtext';
850 }
851
852 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
853 * This could be a username, an ip range, or a single ip. */
854 $intended = $wgUser->mBlock->mAddress;
855
856 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
857
858 # Don't auto-return to special pages
859 if( $return ) {
860 $return = $wgTitle->getNamespace() > -1 ? $wgTitle->getPrefixedText() : NULL;
861 $this->returnToMain( false, $return );
862 }
863 }
864
865 /**
866 * Output a standard error page
867 *
868 * @param string $title Message key for page title
869 * @param string $msg Message key for page text
870 * @param array $params Message parameters
871 */
872 public function showErrorPage( $title, $msg, $params = array() ) {
873 global $wgTitle;
874 if ( isset($wgTitle) ) {
875 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
876 }
877 $this->setPageTitle( wfMsg( $title ) );
878 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
879 $this->setRobotpolicy( 'noindex,nofollow' );
880 $this->setArticleRelated( false );
881 $this->enableClientCache( false );
882 $this->mRedirect = '';
883 $this->mBodytext = '';
884
885 array_unshift( $params, 'parse' );
886 array_unshift( $params, $msg );
887 $this->addHtml( call_user_func_array( 'wfMsgExt', $params ) );
888
889 $this->returnToMain( false );
890 }
891
892 /**
893 * Output a standard permission error page
894 *
895 * @param array $errors Error message keys
896 */
897 public function showPermissionsErrorPage( $errors )
898 {
899 global $wgTitle;
900
901 $this->mDebugtext .= 'Original title: ' .
902 $wgTitle->getPrefixedText() . "\n";
903 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
904 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
905 $this->setRobotpolicy( 'noindex,nofollow' );
906 $this->setArticleRelated( false );
907 $this->enableClientCache( false );
908 $this->mRedirect = '';
909 $this->mBodytext = '';
910 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors ) );
911 }
912
913 /** @deprecated */
914 public function errorpage( $title, $msg ) {
915 throw new ErrorPageError( $title, $msg );
916 }
917
918 /**
919 * Display an error page indicating that a given version of MediaWiki is
920 * required to use it
921 *
922 * @param mixed $version The version of MediaWiki needed to use the page
923 */
924 public function versionRequired( $version ) {
925 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
926 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
927 $this->setRobotpolicy( 'noindex,nofollow' );
928 $this->setArticleRelated( false );
929 $this->mBodytext = '';
930
931 $this->addWikiMsg( 'versionrequiredtext', $version );
932 $this->returnToMain();
933 }
934
935 /**
936 * Display an error page noting that a given permission bit is required.
937 *
938 * @param string $permission key required
939 */
940 public function permissionRequired( $permission ) {
941 global $wgGroupPermissions, $wgUser;
942
943 $this->setPageTitle( wfMsg( 'badaccess' ) );
944 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
945 $this->setRobotpolicy( 'noindex,nofollow' );
946 $this->setArticleRelated( false );
947 $this->mBodytext = '';
948
949 $groups = array();
950 foreach( $wgGroupPermissions as $key => $value ) {
951 if( isset( $value[$permission] ) && $value[$permission] == true ) {
952 $groupName = User::getGroupName( $key );
953 $groupPage = User::getGroupPage( $key );
954 if( $groupPage ) {
955 $skin = $wgUser->getSkin();
956 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
957 } else {
958 $groups[] = $groupName;
959 }
960 }
961 }
962 $n = count( $groups );
963 $groups = implode( ', ', $groups );
964 switch( $n ) {
965 case 0:
966 case 1:
967 case 2:
968 $message = wfMsgHtml( "badaccess-group$n", $groups );
969 break;
970 default:
971 $message = wfMsgHtml( 'badaccess-groups', $groups );
972 }
973 $this->addHtml( $message );
974 $this->returnToMain( false );
975 }
976
977 /**
978 * Use permissionRequired.
979 * @deprecated
980 */
981 public function sysopRequired() {
982 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
983 }
984
985 /**
986 * Use permissionRequired.
987 * @deprecated
988 */
989 public function developerRequired() {
990 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
991 }
992
993 /**
994 * Produce the stock "please login to use the wiki" page
995 */
996 public function loginToUse() {
997 global $wgUser, $wgTitle, $wgContLang;
998
999 if( $wgUser->isLoggedIn() ) {
1000 $this->permissionRequired( 'read' );
1001 return;
1002 }
1003
1004 $skin = $wgUser->getSkin();
1005
1006 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1007 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1008 $this->setRobotPolicy( 'noindex,nofollow' );
1009 $this->setArticleFlag( false );
1010
1011 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1012 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1013 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1014 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1015
1016 # Don't return to the main page if the user can't read it
1017 # otherwise we'll end up in a pointless loop
1018 $mainPage = Title::newMainPage();
1019 if( $mainPage->userCanRead() )
1020 $this->returnToMain( true, $mainPage );
1021 }
1022
1023 /** @deprecated */
1024 public function databaseError( $fname, $sql, $error, $errno ) {
1025 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1026 }
1027
1028 /**
1029 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1030 * @return string The wikitext error-messages, formatted into a list.
1031 */
1032 public function formatPermissionsErrorMessage( $errors ) {
1033 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1034
1035 if (count( $errors ) > 1) {
1036 $text .= '<ul class="permissions-errors">' . "\n";
1037
1038 foreach( $errors as $error )
1039 {
1040 $text .= '<li>';
1041 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1042 $text .= "</li>\n";
1043 }
1044 $text .= '</ul>';
1045 } else {
1046 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', $errors[0]) . '</div>';
1047 }
1048
1049 return $text;
1050 }
1051
1052 /**
1053 * Display a page stating that the Wiki is in read-only mode,
1054 * and optionally show the source of the page that the user
1055 * was trying to edit. Should only be called (for this
1056 * purpose) after wfReadOnly() has returned true.
1057 *
1058 * For historical reasons, this function is _also_ used to
1059 * show the error message when a user tries to edit a page
1060 * they are not allowed to edit. (Unless it's because they're
1061 * blocked, then we show blockedPage() instead.) In this
1062 * case, the second parameter should be set to true and a list
1063 * of reasons supplied as the third parameter.
1064 *
1065 * @todo Needs to be split into multiple functions.
1066 *
1067 * @param string $source Source code to show (or null).
1068 * @param bool $protected Is this a permissions error?
1069 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1070 */
1071 public function readOnlyPage( $source = null, $protected = false, $reasons = array() ) {
1072 global $wgUser, $wgReadOnlyFile, $wgReadOnly, $wgTitle;
1073 $skin = $wgUser->getSkin();
1074
1075 $this->setRobotpolicy( 'noindex,nofollow' );
1076 $this->setArticleRelated( false );
1077
1078 // If no reason is given, just supply a default "I can't let you do
1079 // that, Dave" message. Should only occur if called by legacy code.
1080 if ( $protected && empty($reasons) ) {
1081 $reasons[] = array( 'badaccess-group0' );
1082 }
1083
1084 if ( !empty($reasons) ) {
1085 // Permissions error
1086 if( $source ) {
1087 $this->setPageTitle( wfMsg( 'viewsource' ) );
1088 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1089 } else {
1090 $this->setPageTitle( wfMsg( 'badaccess' ) );
1091 }
1092 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons ) );
1093 } else {
1094 // Wiki is read only
1095 $this->setPageTitle( wfMsg( 'readonly' ) );
1096 if ( $wgReadOnly ) {
1097 $reason = $wgReadOnly;
1098 } else {
1099 // Should not happen, user should have called wfReadOnly() first
1100 $reason = file_get_contents( $wgReadOnlyFile );
1101 }
1102 $this->addWikiMsg( 'readonlytext', $reason );
1103 }
1104
1105 // Show source, if supplied
1106 if( is_string( $source ) ) {
1107 $this->addWikiMsg( 'viewsourcetext' );
1108 $text = wfOpenElement( 'textarea',
1109 array( 'id' => 'wpTextbox1',
1110 'name' => 'wpTextbox1',
1111 'cols' => $wgUser->getOption( 'cols' ),
1112 'rows' => $wgUser->getOption( 'rows' ),
1113 'readonly' => 'readonly' ) );
1114 $text .= htmlspecialchars( $source );
1115 $text .= wfCloseElement( 'textarea' );
1116 $this->addHTML( $text );
1117
1118 // Show templates used by this article
1119 $skin = $wgUser->getSkin();
1120 $article = new Article( $wgTitle );
1121 $this->addHTML( $skin->formatTemplates( $article->getUsedTemplates() ) );
1122 }
1123
1124 # If the title doesn't exist, it's fairly pointless to print a return
1125 # link to it. After all, you just tried editing it and couldn't, so
1126 # what's there to do there?
1127 if( $wgTitle->exists() ) {
1128 $this->returnToMain( false, $wgTitle );
1129 }
1130 }
1131
1132 /** @deprecated */
1133 public function fatalError( $message ) {
1134 throw new FatalError( $message );
1135 }
1136
1137 /** @deprecated */
1138 public function unexpectedValueError( $name, $val ) {
1139 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1140 }
1141
1142 /** @deprecated */
1143 public function fileCopyError( $old, $new ) {
1144 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1145 }
1146
1147 /** @deprecated */
1148 public function fileRenameError( $old, $new ) {
1149 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1150 }
1151
1152 /** @deprecated */
1153 public function fileDeleteError( $name ) {
1154 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1155 }
1156
1157 /** @deprecated */
1158 public function fileNotFoundError( $name ) {
1159 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1160 }
1161
1162 public function showFatalError( $message ) {
1163 $this->setPageTitle( wfMsg( "internalerror" ) );
1164 $this->setRobotpolicy( "noindex,nofollow" );
1165 $this->setArticleRelated( false );
1166 $this->enableClientCache( false );
1167 $this->mRedirect = '';
1168 $this->mBodytext = $message;
1169 }
1170
1171 public function showUnexpectedValueError( $name, $val ) {
1172 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1173 }
1174
1175 public function showFileCopyError( $old, $new ) {
1176 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1177 }
1178
1179 public function showFileRenameError( $old, $new ) {
1180 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1181 }
1182
1183 public function showFileDeleteError( $name ) {
1184 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1185 }
1186
1187 public function showFileNotFoundError( $name ) {
1188 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1189 }
1190
1191 /**
1192 * Add a "return to" link pointing to a specified title
1193 *
1194 * @param Title $title Title to link
1195 */
1196 public function addReturnTo( $title ) {
1197 global $wgUser;
1198 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1199 $this->addHtml( "<p>{$link}</p>\n" );
1200 }
1201
1202 /**
1203 * Add a "return to" link pointing to a specified title,
1204 * or the title indicated in the request, or else the main page
1205 *
1206 * @param null $unused No longer used
1207 * @param Title $returnto Title to return to
1208 */
1209 public function returnToMain( $unused = null, $returnto = NULL ) {
1210 global $wgRequest;
1211
1212 if ( $returnto == NULL ) {
1213 $returnto = $wgRequest->getText( 'returnto' );
1214 }
1215
1216 if ( '' === $returnto ) {
1217 $returnto = Title::newMainPage();
1218 }
1219
1220 if ( is_object( $returnto ) ) {
1221 $titleObj = $returnto;
1222 } else {
1223 $titleObj = Title::newFromText( $returnto );
1224 }
1225 if ( !is_object( $titleObj ) ) {
1226 $titleObj = Title::newMainPage();
1227 }
1228
1229 $this->addReturnTo( $titleObj );
1230 }
1231
1232 /**
1233 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1234 * and uses the first 10 of them for META keywords
1235 *
1236 * @param ParserOutput &$parserOutput
1237 */
1238 private function addKeywords( &$parserOutput ) {
1239 global $wgTitle;
1240 $this->addKeyword( $wgTitle->getPrefixedText() );
1241 $count = 1;
1242 $links2d =& $parserOutput->getLinks();
1243 if ( !is_array( $links2d ) ) {
1244 return;
1245 }
1246 foreach ( $links2d as $dbkeys ) {
1247 foreach( $dbkeys as $dbkey => $unused ) {
1248 $this->addKeyword( $dbkey );
1249 if ( ++$count > 10 ) {
1250 break 2;
1251 }
1252 }
1253 }
1254 }
1255
1256 /**
1257 * @return string The doctype, opening <html>, and head element.
1258 */
1259 public function headElement() {
1260 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1261 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1262 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1263
1264 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1265 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1266 } else {
1267 $ret = '';
1268 }
1269
1270 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1271
1272 if ( '' == $this->getHTMLTitle() ) {
1273 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1274 }
1275
1276 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1277 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1278 foreach($wgXhtmlNamespaces as $tag => $ns) {
1279 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1280 }
1281 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1282 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1283 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
1284
1285 $ret .= $this->getHeadLinks();
1286 global $wgStylePath;
1287 if( $this->isPrintable() ) {
1288 $media = '';
1289 } else {
1290 $media = "media='print'";
1291 }
1292 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1293 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1294
1295 $sk = $wgUser->getSkin();
1296 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1297 $ret .= $this->mScripts;
1298 $ret .= $sk->getUserStyles();
1299 $ret .= $this->getHeadItems();
1300
1301 if ($wgUseTrackbacks && $this->isArticleRelated())
1302 $ret .= $wgTitle->trackbackRDF();
1303
1304 $ret .= "</head>\n";
1305 return $ret;
1306 }
1307
1308 /**
1309 * @return string HTML tag links to be put in the header.
1310 */
1311 public function getHeadLinks() {
1312 global $wgRequest;
1313 $ret = '';
1314 foreach ( $this->mMetatags as $tag ) {
1315 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1316 $a = 'http-equiv';
1317 $tag[0] = substr( $tag[0], 5 );
1318 } else {
1319 $a = 'name';
1320 }
1321 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
1322 }
1323
1324 $p = $this->mRobotpolicy;
1325 if( $p !== '' && $p != 'index,follow' ) {
1326 // http://www.robotstxt.org/wc/meta-user.html
1327 // Only show if it's different from the default robots policy
1328 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
1329 }
1330
1331 if ( count( $this->mKeywords ) > 0 ) {
1332 $strip = array(
1333 "/<.*?>/" => '',
1334 "/_/" => ' '
1335 );
1336 $ret .= "\t\t<meta name=\"keywords\" content=\"" .
1337 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
1338 }
1339 foreach ( $this->mLinktags as $tag ) {
1340 $ret .= "\t\t<link";
1341 foreach( $tag as $attr => $val ) {
1342 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
1343 }
1344 $ret .= " />\n";
1345 }
1346
1347 foreach( $this->getSyndicationLinks() as $format => $link ) {
1348 # Use the page name for the title (accessed through $wgTitle since
1349 # there's no other way). In principle, this could lead to issues
1350 # with having the same name for different feeds corresponding to
1351 # the same page, but we can't avoid that at this low a level.
1352 global $wgTitle;
1353
1354 $ret .= $this->feedLink(
1355 $format,
1356 $link,
1357 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1358 }
1359
1360 # Recent changes feed should appear on every page
1361 # Put it after the per-page feed to avoid changing existing behavior.
1362 # It's still available, probably via a menu in your browser.
1363 global $wgSitename;
1364 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1365 $ret .= $this->feedLink(
1366 'rss',
1367 $rctitle->getFullURL( 'feed=rss' ),
1368 wfMsg( 'site-rss-feed', $wgSitename ) );
1369 $ret .= $this->feedLink(
1370 'atom',
1371 $rctitle->getFullURL( 'feed=atom' ),
1372 wfMsg( 'site-atom-feed', $wgSitename ) );
1373
1374 return $ret;
1375 }
1376
1377 /**
1378 * Return URLs for each supported syndication format for this page.
1379 * @return array associating format keys with URLs
1380 */
1381 public function getSyndicationLinks() {
1382 global $wgTitle, $wgFeedClasses;
1383 $links = array();
1384
1385 if( $this->isSyndicated() ) {
1386 if( is_string( $this->getFeedAppendQuery() ) ) {
1387 $appendQuery = "&" . $this->getFeedAppendQuery();
1388 } else {
1389 $appendQuery = "";
1390 }
1391
1392 foreach( $wgFeedClasses as $format => $class ) {
1393 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1394 }
1395 }
1396 return $links;
1397 }
1398
1399 /**
1400 * Generate a <link rel/> for an RSS feed.
1401 */
1402 private function feedLink( $type, $url, $text ) {
1403 return Xml::element( 'link', array(
1404 'rel' => 'alternate',
1405 'type' => "application/$type+xml",
1406 'title' => $text,
1407 'href' => $url ) ) . "\n";
1408 }
1409
1410 /**
1411 * Turn off regular page output and return an error reponse
1412 * for when rate limiting has triggered.
1413 */
1414 public function rateLimited() {
1415 global $wgOut, $wgTitle;
1416
1417 $this->setPageTitle(wfMsg('actionthrottled'));
1418 $this->setRobotPolicy( 'noindex,follow' );
1419 $this->setArticleRelated( false );
1420 $this->enableClientCache( false );
1421 $this->mRedirect = '';
1422 $this->clearHTML();
1423 $this->setStatusCode(503);
1424 $this->addWikiMsg( 'actionthrottledtext' );
1425
1426 $this->returnToMain( false, $wgTitle );
1427 }
1428
1429 /**
1430 * Show an "add new section" link?
1431 *
1432 * @return bool
1433 */
1434 public function showNewSectionLink() {
1435 return $this->mNewSectionLink;
1436 }
1437
1438 /**
1439 * Show a warning about slave lag
1440 *
1441 * If the lag is higher than $wgSlaveLagCritical seconds,
1442 * then the warning is a bit more obvious. If the lag is
1443 * lower than $wgSlaveLagWarning, then no warning is shown.
1444 *
1445 * @param int $lag Slave lag
1446 */
1447 public function showLagWarning( $lag ) {
1448 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1449 if( $lag >= $wgSlaveLagWarning ) {
1450 $message = $lag < $wgSlaveLagCritical
1451 ? 'lag-warn-normal'
1452 : 'lag-warn-high';
1453 $warning = wfMsgExt( $message, 'parse', $lag );
1454 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1455 }
1456 }
1457
1458 /**
1459 * Add a wikitext-formatted message to the output.
1460 * This is equivalent to:
1461 *
1462 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1463 */
1464 public function addWikiMsg( /*...*/ ) {
1465 $args = func_get_args();
1466 $name = array_shift( $args );
1467 $this->addWikiMsgArray( $name, $args );
1468 }
1469
1470 /**
1471 * Add a wikitext-formatted message to the output.
1472 * Like addWikiMsg() except the parameters are taken as an array
1473 * instead of a variable argument list.
1474 *
1475 * $options is passed through to wfMsgExt(), see that function for details.
1476 */
1477 public function addWikiMsgArray( $name, $args, $options = array() ) {
1478 $options[] = 'parse';
1479 $text = wfMsgExt( $name, $options, $args );
1480 $this->addHTML( $text );
1481 }
1482
1483 /**
1484 * This function takes a number of message/argument specifications, wraps them in
1485 * some overall structure, and then parses the result and adds it to the output.
1486 *
1487 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1488 * on. The subsequent arguments may either be strings, in which case they are the
1489 * message names, or an arrays, in which case the first element is the message name,
1490 * and subsequent elements are the parameters to that message.
1491 *
1492 * The special named parameter 'options' in a message specification array is passed
1493 * through to the $options parameter of wfMsgExt().
1494 *
1495 * For example:
1496 *
1497 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1498 *
1499 * Is equivalent to:
1500 *
1501 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1502 */
1503 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1504 $msgSpecs = func_get_args();
1505 array_shift( $msgSpecs );
1506 $msgSpecs = array_values( $msgSpecs );
1507 $s = $wrap;
1508 foreach ( $msgSpecs as $n => $spec ) {
1509 $options = array();
1510 if ( is_array( $spec ) ) {
1511 $args = $spec;
1512 $name = array_shift( $args );
1513 if ( isset( $args['options'] ) ) {
1514 $options = $args['options'];
1515 unset( $args['options'] );
1516 }
1517 } else {
1518 $args = array();
1519 $name = $spec;
1520 }
1521 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1522 }
1523 $this->addHTML( $this->parse( $s ) );
1524 }
1525 }