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