Update.
[mediawiki.git] / includes / OutputPage.php
blob39d713187f8328f1479cdda0e2833bdbc42ee2b7
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
4 /**
5 */
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;
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 $mEnableClientCache = true;
27 var $mArticleBodyOnly = false;
29 var $mNewSectionLink = false;
30 var $mNoGallery = false;
31 var $mPageTitleActionText = '';
33 /**
34 * Constructor
35 * Initialise private variables
37 function __construct() {
38 global $wgAllowUserJs;
39 $this->mAllowUserJs = $wgAllowUserJs;
40 $this->mMetatags = $this->mKeywords = $this->mLinktags = array();
41 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
42 $this->mRedirect = $this->mLastModified =
43 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
44 $this->mOnloadHandler = $this->mPageLinkTitle = '';
45 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
46 $this->mSuppressQuickbar = $this->mPrintable = false;
47 $this->mLanguageLinks = array();
48 $this->mCategoryLinks = array();
49 $this->mDoNothing = false;
50 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
51 $this->mParserOptions = null;
52 $this->mSquidMaxage = 0;
53 $this->mScripts = '';
54 $this->mHeadItems = array();
55 $this->mETag = false;
56 $this->mRevisionId = null;
57 $this->mNewSectionLink = false;
58 $this->mTemplateIds = array();
61 public function redirect( $url, $responsecode = '302' ) {
62 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
63 $this->mRedirect = str_replace( "\n", '', $url );
64 $this->mRedirectCode = $responsecode;
67 /**
68 * Set the HTTP status code to send with the output.
70 * @param int $statusCode
71 * @return nothing
73 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
75 # To add an http-equiv meta tag, precede the name with "http:"
76 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
77 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
78 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
79 function addStyle( $style ) {
80 global $wgStylePath, $wgStyleVersion;
81 $this->addLink(
82 array(
83 'rel' => 'stylesheet',
84 'href' => $wgStylePath . '/' . $style . '?' . $wgStyleVersion ) );
87 /**
88 * Add a self-contained script tag with the given contents
89 * @param string $script JavaScript text, no <script> tags
91 function addInlineScript( $script ) {
92 global $wgJsMimeType;
93 $this->mScripts .= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
96 function getScript() {
97 return $this->mScripts . $this->getHeadItems();
100 function getHeadItems() {
101 $s = '';
102 foreach ( $this->mHeadItems as $item ) {
103 $s .= $item;
105 return $s;
108 function addHeadItem( $name, $value ) {
109 $this->mHeadItems[$name] = $value;
112 function setETag($tag) { $this->mETag = $tag; }
113 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
114 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
116 function addLink( $linkarr ) {
117 # $linkarr should be an associative array of attributes. We'll escape on output.
118 array_push( $this->mLinktags, $linkarr );
121 function addMetadataLink( $linkarr ) {
122 # note: buggy CC software only reads first "meta" link
123 static $haveMeta = false;
124 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
125 $this->addLink( $linkarr );
126 $haveMeta = true;
130 * checkLastModified tells the client to use the client-cached page if
131 * possible. If sucessful, the OutputPage is disabled so that
132 * any future call to OutputPage->output() have no effect.
134 * @return bool True iff cache-ok headers was sent.
136 function checkLastModified ( $timestamp ) {
137 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
138 $fname = 'OutputPage::checkLastModified';
140 if ( !$timestamp || $timestamp == '19700101000000' ) {
141 wfDebug( "$fname: CACHE DISABLED, NO TIMESTAMP\n" );
142 return;
144 if( !$wgCachePages ) {
145 wfDebug( "$fname: CACHE DISABLED\n", false );
146 return;
148 if( $wgUser->getOption( 'nocache' ) ) {
149 wfDebug( "$fname: USER DISABLED CACHE\n", false );
150 return;
153 $timestamp=wfTimestamp(TS_MW,$timestamp);
154 $lastmod = wfTimestamp( TS_RFC2822, max( $timestamp, $wgUser->mTouched, $wgCacheEpoch ) );
156 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
157 # IE sends sizes after the date like this:
158 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
159 # this breaks strtotime().
160 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
162 wfSuppressWarnings(); // E_STRICT system time bitching
163 $modsinceTime = strtotime( $modsince );
164 wfRestoreWarnings();
166 $ismodsince = wfTimestamp( TS_MW, $modsinceTime ? $modsinceTime : 1 );
167 wfDebug( "$fname: -- client send If-Modified-Since: " . $modsince . "\n", false );
168 wfDebug( "$fname: -- we might send Last-Modified : $lastmod\n", false );
169 if( ($ismodsince >= $timestamp ) && $wgUser->validateCache( $ismodsince ) && $ismodsince >= $wgCacheEpoch ) {
170 # Make sure you're in a place you can leave when you call us!
171 $wgRequest->response()->header( "HTTP/1.0 304 Not Modified" );
172 $this->mLastModified = $lastmod;
173 $this->sendCacheControl();
174 wfDebug( "$fname: CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
175 $this->disable();
177 // Don't output a compressed blob when using ob_gzhandler;
178 // it's technically against HTTP spec and seems to confuse
179 // Firefox when the response gets split over two packets.
180 wfClearOutputBuffers();
182 return true;
183 } else {
184 wfDebug( "$fname: READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
185 $this->mLastModified = $lastmod;
187 } else {
188 wfDebug( "$fname: client did not send If-Modified-Since header\n", false );
189 $this->mLastModified = $lastmod;
193 function setPageTitleActionText( $text ) {
194 $this->mPageTitleActionText = $text;
197 function getPageTitleActionText () {
198 if ( isset( $this->mPageTitleActionText ) ) {
199 return $this->mPageTitleActionText;
203 public function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
204 public function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
205 public function setPageTitle( $name ) {
206 global $action, $wgContLang;
207 $name = $wgContLang->convert($name, true);
208 $this->mPagetitle = $name;
209 if(!empty($action)) {
210 $taction = $this->getPageTitleActionText();
211 if( !empty( $taction ) ) {
212 $name .= ' - '.$taction;
216 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
218 public function getHTMLTitle() { return $this->mHTMLtitle; }
219 public function getPageTitle() { return $this->mPagetitle; }
220 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
221 public function getSubtitle() { return $this->mSubtitle; }
222 public function isArticle() { return $this->mIsarticle; }
223 public function setPrintable() { $this->mPrintable = true; }
224 public function isPrintable() { return $this->mPrintable; }
225 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
226 public function isSyndicated() { return $this->mShowFeedLinks; }
227 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
228 public function getOnloadHandler() { return $this->mOnloadHandler; }
229 public function disable() { $this->mDoNothing = true; }
231 public function setArticleRelated( $v ) {
232 $this->mIsArticleRelated = $v;
233 if ( !$v ) {
234 $this->mIsarticle = false;
237 public function setArticleFlag( $v ) {
238 $this->mIsarticle = $v;
239 if ( $v ) {
240 $this->mIsArticleRelated = $v;
244 public function isArticleRelated() { return $this->mIsArticleRelated; }
246 public function getLanguageLinks() { return $this->mLanguageLinks; }
247 public function addLanguageLinks($newLinkArray) {
248 $this->mLanguageLinks += $newLinkArray;
250 public function setLanguageLinks($newLinkArray) {
251 $this->mLanguageLinks = $newLinkArray;
254 public function getCategoryLinks() {
255 return $this->mCategoryLinks;
259 * Add an array of categories, with names in the keys
261 public function addCategoryLinks($categories) {
262 global $wgUser, $wgContLang;
264 if ( !is_array( $categories ) ) {
265 return;
267 # Add the links to the link cache in a batch
268 $arr = array( NS_CATEGORY => $categories );
269 $lb = new LinkBatch;
270 $lb->setArray( $arr );
271 $lb->execute();
273 $sk = $wgUser->getSkin();
274 foreach ( $categories as $category => $unused ) {
275 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
276 $text = $wgContLang->convertHtml( $title->getText() );
277 $this->mCategoryLinks[] = $sk->makeLinkObj( $title, $text );
281 public function setCategoryLinks($categories) {
282 $this->mCategoryLinks = array();
283 $this->addCategoryLinks($categories);
286 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
287 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
289 public function disallowUserJs() { $this->mAllowUserJs = false; }
290 public function isUserJsAllowed() { return $this->mAllowUserJs; }
292 public function addHTML( $text ) { $this->mBodytext .= $text; }
293 public function clearHTML() { $this->mBodytext = ''; }
294 public function getHTML() { return $this->mBodytext; }
295 public function debug( $text ) { $this->mDebugtext .= $text; }
297 /* @deprecated */
298 public function setParserOptions( $options ) {
299 return $this->parserOptions( $options );
302 public function parserOptions( $options = null ) {
303 if ( !$this->mParserOptions ) {
304 $this->mParserOptions = new ParserOptions;
306 return wfSetVar( $this->mParserOptions, $options );
310 * Set the revision ID which will be seen by the wiki text parser
311 * for things such as embedded {{REVISIONID}} variable use.
312 * @param mixed $revid an integer, or NULL
313 * @return mixed previous value
315 public function setRevisionId( $revid ) {
316 $val = is_null( $revid ) ? null : intval( $revid );
317 return wfSetVar( $this->mRevisionId, $val );
321 * Convert wikitext to HTML and add it to the buffer
322 * Default assumes that the current page title will
323 * be used.
325 * @param string $text
326 * @param bool $linestart
328 public function addWikiText( $text, $linestart = true ) {
329 global $wgTitle;
330 $this->addWikiTextTitle($text, $wgTitle, $linestart);
333 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
334 $this->addWikiTextTitle($text, $title, $linestart);
337 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
338 $this->addWikiTextTitle( $text, $title, $linestart, true );
341 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
342 global $wgParser;
344 $fname = 'OutputPage:addWikiTextTitle';
345 wfProfileIn($fname);
347 wfIncrStats('pcache_not_possible');
349 $popts = $this->parserOptions();
350 $popts->setTidy($tidy);
352 $parserOutput = $wgParser->parse( $text, $title, $popts,
353 $linestart, true, $this->mRevisionId );
355 $this->addParserOutput( $parserOutput );
357 wfProfileOut($fname);
361 * @todo document
362 * @param ParserOutput object &$parserOutput
364 public function addParserOutputNoText( &$parserOutput ) {
365 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
366 $this->addCategoryLinks( $parserOutput->getCategories() );
367 $this->mNewSectionLink = $parserOutput->getNewSection();
368 $this->addKeywords( $parserOutput );
369 if ( $parserOutput->getCacheTime() == -1 ) {
370 $this->enableClientCache( false );
372 $this->mNoGallery = $parserOutput->getNoGallery();
373 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
374 // Versioning...
375 $this->mTemplateIds += (array)$parserOutput->mTemplateIds;
377 # Display title
378 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
379 $this->setPageTitle( $dt );
381 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
385 * @todo document
386 * @param ParserOutput &$parserOutput
388 function addParserOutput( &$parserOutput ) {
389 $this->addParserOutputNoText( $parserOutput );
390 $text = $parserOutput->getText();
391 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
392 $this->addHTML( $text );
396 * Add wikitext to the buffer, assuming that this is the primary text for a page view
397 * Saves the text into the parser cache if possible.
399 * @param string $text
400 * @param Article $article
401 * @param bool $cache
402 * @deprecated Use Article::outputWikitext
404 public function addPrimaryWikiText( $text, $article, $cache = true ) {
405 global $wgParser, $wgUser;
407 $popts = $this->parserOptions();
408 $popts->setTidy(true);
409 $parserOutput = $wgParser->parse( $text, $article->mTitle,
410 $popts, true, true, $this->mRevisionId );
411 $popts->setTidy(false);
412 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
413 $parserCache =& ParserCache::singleton();
414 $parserCache->save( $parserOutput, $article, $wgUser );
417 $this->addParserOutput( $parserOutput );
421 * @deprecated use addWikiTextTidy()
423 public function addSecondaryWikiText( $text, $linestart = true ) {
424 global $wgTitle;
425 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
429 * Add wikitext with tidy enabled
431 public function addWikiTextTidy( $text, $linestart = true ) {
432 global $wgTitle;
433 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
438 * Add the output of a QuickTemplate to the output buffer
440 * @param QuickTemplate $template
442 public function addTemplate( &$template ) {
443 ob_start();
444 $template->execute();
445 $this->addHTML( ob_get_contents() );
446 ob_end_clean();
450 * Parse wikitext and return the HTML.
452 * @param string $text
453 * @param bool $linestart Is this the start of a line?
454 * @param bool $interface ??
456 public function parse( $text, $linestart = true, $interface = false ) {
457 global $wgParser, $wgTitle;
458 $popts = $this->parserOptions();
459 if ( $interface) { $popts->setInterfaceMessage(true); }
460 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
461 $linestart, true, $this->mRevisionId );
462 if ( $interface) { $popts->setInterfaceMessage(false); }
463 return $parserOutput->getText();
467 * @param Article $article
468 * @param User $user
470 * @return bool True if successful, else false.
472 public function tryParserCache( &$article, $user ) {
473 $parserCache =& ParserCache::singleton();
474 $parserOutput = $parserCache->get( $article, $user );
475 if ( $parserOutput !== false ) {
476 $this->addParserOutput( $parserOutput );
477 return true;
478 } else {
479 return false;
484 * @param int $maxage Maximum cache time on the Squid, in seconds.
486 public function setSquidMaxage( $maxage ) {
487 $this->mSquidMaxage = $maxage;
491 * Use enableClientCache(false) to force it to send nocache headers
492 * @param $state ??
494 public function enableClientCache( $state ) {
495 return wfSetVar( $this->mEnableClientCache, $state );
498 function uncacheableBecauseRequestvars() {
499 global $wgRequest;
500 return $wgRequest->getText('useskin', false) === false
501 && $wgRequest->getText('uselang', false) === false;
504 public function sendCacheControl() {
505 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
506 $fname = 'OutputPage::sendCacheControl';
508 if ($wgUseETag && $this->mETag)
509 $wgRequest->response()->header("ETag: $this->mETag");
511 # don't serve compressed data to clients who can't handle it
512 # maintain different caches for logged-in users and non-logged in ones
513 $wgRequest->response()->header( 'Vary: Accept-Encoding, Cookie' );
514 if( !$this->uncacheableBecauseRequestvars() && $this->mEnableClientCache ) {
515 if( $wgUseSquid && session_id() == '' &&
516 ! $this->isPrintable() && $this->mSquidMaxage != 0 )
518 if ( $wgUseESI ) {
519 # We'll purge the proxy cache explicitly, but require end user agents
520 # to revalidate against the proxy on each visit.
521 # Surrogate-Control controls our Squid, Cache-Control downstream caches
522 wfDebug( "$fname: proxy caching with ESI; {$this->mLastModified} **\n", false );
523 # start with a shorter timeout for initial testing
524 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
525 $wgRequest->response()->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
526 $wgRequest->response()->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
527 } else {
528 # We'll purge the proxy cache for anons explicitly, but require end user agents
529 # to revalidate against the proxy on each visit.
530 # IMPORTANT! The Squid needs to replace the Cache-Control header with
531 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
532 wfDebug( "$fname: local proxy caching; {$this->mLastModified} **\n", false );
533 # start with a shorter timeout for initial testing
534 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
535 $wgRequest->response()->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
537 } else {
538 # We do want clients to cache if they can, but they *must* check for updates
539 # on revisiting the page.
540 wfDebug( "$fname: private caching; {$this->mLastModified} **\n", false );
541 $wgRequest->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
542 $wgRequest->response()->header( "Cache-Control: private, must-revalidate, max-age=0" );
544 if($this->mLastModified) $wgRequest->response()->header( "Last-modified: {$this->mLastModified}" );
545 } else {
546 wfDebug( "$fname: no caching **\n", false );
548 # In general, the absence of a last modified header should be enough to prevent
549 # the client from using its cache. We send a few other things just to make sure.
550 $wgRequest->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
551 $wgRequest->response()->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
552 $wgRequest->response()->header( 'Pragma: no-cache' );
557 * Finally, all the text has been munged and accumulated into
558 * the object, let's actually output it:
560 public function output() {
561 global $wgUser, $wgOutputEncoding, $wgRequest;
562 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
563 global $wgJsMimeType, $wgStylePath, $wgUseAjax, $wgAjaxSearch, $wgAjaxWatch;
564 global $wgServer, $wgStyleVersion;
566 if( $this->mDoNothing ){
567 return;
569 $fname = 'OutputPage::output';
570 wfProfileIn( $fname );
571 $sk = $wgUser->getSkin();
573 if ( $wgUseAjax ) {
574 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajax.js?$wgStyleVersion\"></script>\n" );
576 wfRunHooks( 'AjaxAddScript', array( &$this ) );
578 if( $wgAjaxSearch ) {
579 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxsearch.js?$wgStyleVersion\"></script>\n" );
580 $this->addScript( "<script type=\"{$wgJsMimeType}\">hookEvent(\"load\", sajax_onload);</script>\n" );
583 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
584 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxwatch.js?$wgStyleVersion\"></script>\n" );
588 if ( '' != $this->mRedirect ) {
589 if( substr( $this->mRedirect, 0, 4 ) != 'http' ) {
590 # Standards require redirect URLs to be absolute
591 global $wgServer;
592 $this->mRedirect = $wgServer . $this->mRedirect;
594 if( $this->mRedirectCode == '301') {
595 if( !$wgDebugRedirects ) {
596 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
598 $this->mLastModified = wfTimestamp( TS_RFC2822 );
601 $this->sendCacheControl();
603 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
604 if( $wgDebugRedirects ) {
605 $url = htmlspecialchars( $this->mRedirect );
606 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
607 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
608 print "</body>\n</html>\n";
609 } else {
610 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
612 wfProfileOut( $fname );
613 return;
615 elseif ( $this->mStatusCode )
617 $statusMessage = array(
618 100 => 'Continue',
619 101 => 'Switching Protocols',
620 102 => 'Processing',
621 200 => 'OK',
622 201 => 'Created',
623 202 => 'Accepted',
624 203 => 'Non-Authoritative Information',
625 204 => 'No Content',
626 205 => 'Reset Content',
627 206 => 'Partial Content',
628 207 => 'Multi-Status',
629 300 => 'Multiple Choices',
630 301 => 'Moved Permanently',
631 302 => 'Found',
632 303 => 'See Other',
633 304 => 'Not Modified',
634 305 => 'Use Proxy',
635 307 => 'Temporary Redirect',
636 400 => 'Bad Request',
637 401 => 'Unauthorized',
638 402 => 'Payment Required',
639 403 => 'Forbidden',
640 404 => 'Not Found',
641 405 => 'Method Not Allowed',
642 406 => 'Not Acceptable',
643 407 => 'Proxy Authentication Required',
644 408 => 'Request Timeout',
645 409 => 'Conflict',
646 410 => 'Gone',
647 411 => 'Length Required',
648 412 => 'Precondition Failed',
649 413 => 'Request Entity Too Large',
650 414 => 'Request-URI Too Large',
651 415 => 'Unsupported Media Type',
652 416 => 'Request Range Not Satisfiable',
653 417 => 'Expectation Failed',
654 422 => 'Unprocessable Entity',
655 423 => 'Locked',
656 424 => 'Failed Dependency',
657 500 => 'Internal Server Error',
658 501 => 'Not Implemented',
659 502 => 'Bad Gateway',
660 503 => 'Service Unavailable',
661 504 => 'Gateway Timeout',
662 505 => 'HTTP Version Not Supported',
663 507 => 'Insufficient Storage'
666 if ( $statusMessage[$this->mStatusCode] )
667 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
670 # Buffer output; final headers may depend on later processing
671 ob_start();
673 # Disable temporary placeholders, so that the skin produces HTML
674 $sk->postParseLinkColour( false );
676 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
677 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
679 if ($this->mArticleBodyOnly) {
680 $this->out($this->mBodytext);
681 } else {
682 wfProfileIn( 'Output-skin' );
683 $sk->outputPage( $this );
684 wfProfileOut( 'Output-skin' );
687 $this->sendCacheControl();
688 ob_end_flush();
689 wfProfileOut( $fname );
693 * @todo document
694 * @param string $ins
696 public function out( $ins ) {
697 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
698 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
699 $outs = $ins;
700 } else {
701 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
702 if ( false === $outs ) { $outs = $ins; }
704 print $outs;
708 * @todo document
710 public static function setEncodings() {
711 global $wgInputEncoding, $wgOutputEncoding;
712 global $wgUser, $wgContLang;
714 $wgInputEncoding = strtolower( $wgInputEncoding );
716 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
717 $wgOutputEncoding = strtolower( $wgOutputEncoding );
718 return;
720 $wgOutputEncoding = $wgInputEncoding;
724 * Deprecated, use wfReportTime() instead.
725 * @return string
726 * @deprecated
728 public function reportTime() {
729 $time = wfReportTime();
730 return $time;
734 * Produce a "user is blocked" page.
736 * @param bool $return Whether to have a "return to $wgTitle" message or not.
737 * @return nothing
739 function blockedPage( $return = true ) {
740 global $wgUser, $wgContLang, $wgTitle, $wgLang;
742 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
743 $this->setRobotpolicy( 'noindex,nofollow' );
744 $this->setArticleRelated( false );
746 $id = $wgUser->blockedBy();
747 $reason = $wgUser->blockedFor();
748 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
749 $ip = wfGetIP();
751 if ( is_numeric( $id ) ) {
752 $name = User::whoIs( $id );
753 } else {
754 $name = $id;
756 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
758 $blockid = $wgUser->mBlock->mId;
760 $blockExpiry = $wgUser->mBlock->mExpiry;
761 if ( $blockExpiry == 'infinity' ) {
762 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
763 // Search for localization in 'ipboptions'
764 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
765 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
766 if ( strpos( $option, ":" ) === false )
767 continue;
768 list( $show, $value ) = explode( ":", $option );
769 if ( $value == 'infinite' || $value == 'indefinite' ) {
770 $blockExpiry = $show;
771 break;
774 } else {
775 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
778 if ( $wgUser->mBlock->mAuto ) {
779 $msg = 'autoblockedtext';
780 } else {
781 $msg = 'blockedtext';
784 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
785 * This could be a username, an ip range, or a single ip. */
786 $intended = $wgUser->mBlock->mAddress;
788 $this->addWikiText( wfMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp ) );
790 # Don't auto-return to special pages
791 if( $return ) {
792 $return = $wgTitle->getNamespace() > -1 ? $wgTitle->getPrefixedText() : NULL;
793 $this->returnToMain( false, $return );
798 * Output a standard error page
800 * @param string $title Message key for page title
801 * @param string $msg Message key for page text
802 * @param array $params Message parameters
804 public function showErrorPage( $title, $msg, $params = array() ) {
805 global $wgTitle;
807 $this->mDebugtext .= 'Original title: ' .
808 $wgTitle->getPrefixedText() . "\n";
809 $this->setPageTitle( wfMsg( $title ) );
810 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
811 $this->setRobotpolicy( 'noindex,nofollow' );
812 $this->setArticleRelated( false );
813 $this->enableClientCache( false );
814 $this->mRedirect = '';
815 $this->mBodytext = '';
817 array_unshift( $params, $msg );
818 $message = call_user_func_array( 'wfMsg', $params );
819 $this->addWikiText( $message );
821 $this->returnToMain( false );
824 /** @deprecated */
825 public function errorpage( $title, $msg ) {
826 throw new ErrorPageError( $title, $msg );
830 * Display an error page indicating that a given version of MediaWiki is
831 * required to use it
833 * @param mixed $version The version of MediaWiki needed to use the page
835 public function versionRequired( $version ) {
836 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
837 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
838 $this->setRobotpolicy( 'noindex,nofollow' );
839 $this->setArticleRelated( false );
840 $this->mBodytext = '';
842 $this->addWikiText( wfMsg( 'versionrequiredtext', $version ) );
843 $this->returnToMain();
847 * Display an error page noting that a given permission bit is required.
849 * @param string $permission key required
851 public function permissionRequired( $permission ) {
852 global $wgGroupPermissions, $wgUser;
854 $this->setPageTitle( wfMsg( 'badaccess' ) );
855 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
856 $this->setRobotpolicy( 'noindex,nofollow' );
857 $this->setArticleRelated( false );
858 $this->mBodytext = '';
860 $groups = array();
861 foreach( $wgGroupPermissions as $key => $value ) {
862 if( isset( $value[$permission] ) && $value[$permission] == true ) {
863 $groupName = User::getGroupName( $key );
864 $groupPage = User::getGroupPage( $key );
865 if( $groupPage ) {
866 $skin = $wgUser->getSkin();
867 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
868 } else {
869 $groups[] = $groupName;
873 $n = count( $groups );
874 $groups = implode( ', ', $groups );
875 switch( $n ) {
876 case 0:
877 case 1:
878 case 2:
879 $message = wfMsgHtml( "badaccess-group$n", $groups );
880 break;
881 default:
882 $message = wfMsgHtml( 'badaccess-groups', $groups );
884 $this->addHtml( $message );
885 $this->returnToMain( false );
889 * Use permissionRequired.
890 * @deprecated
892 public function sysopRequired() {
893 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
897 * Use permissionRequired.
898 * @deprecated
900 public function developerRequired() {
901 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
905 * Produce the stock "please login to use the wiki" page
907 public function loginToUse() {
908 global $wgUser, $wgTitle, $wgContLang;
910 if( $wgUser->isLoggedIn() ) {
911 $this->permissionRequired( 'read' );
912 return;
915 $skin = $wgUser->getSkin();
917 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
918 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
919 $this->setRobotPolicy( 'noindex,nofollow' );
920 $this->setArticleFlag( false );
922 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
923 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
924 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
925 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
927 # Don't return to the main page if the user can't read it
928 # otherwise we'll end up in a pointless loop
929 $mainPage = Title::newMainPage();
930 if( $mainPage->userCanRead() )
931 $this->returnToMain( true, $mainPage );
934 /** @deprecated */
935 public function databaseError( $fname, $sql, $error, $errno ) {
936 throw new MWException( "OutputPage::databaseError is obsolete\n" );
940 * @todo document
941 * @param bool $protected Is the reason the page can't be reached because it's protected?
942 * @param mixed $source
944 public function readOnlyPage( $source = null, $protected = false ) {
945 global $wgUser, $wgReadOnlyFile, $wgReadOnly, $wgTitle;
946 $skin = $wgUser->getSkin();
948 $this->setRobotpolicy( 'noindex,nofollow' );
949 $this->setArticleRelated( false );
951 if( $protected ) {
952 $this->setPageTitle( wfMsg( 'viewsource' ) );
953 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
954 list( $cascadeSources, /* $restrictions */ ) = $wgTitle->getCascadeProtectionSources();
956 // Show an appropriate explanation depending upon the reason
957 // for the protection...all of these should be moved to the
958 // callers
959 if( $wgTitle->getNamespace() == NS_MEDIAWIKI ) {
960 // User isn't allowed to edit the interface
961 $this->addWikiText( wfMsg( 'protectedinterface' ) );
962 } elseif( $cascadeSources && ( $count = count( $cascadeSources ) ) > 0 ) {
963 // Cascading protection
964 $titles = '';
965 foreach( $cascadeSources as $title )
966 $titles .= "* [[:" . $title->getPrefixedText() . "]]\n";
967 $this->addWikiText( wfMsgExt( 'cascadeprotected', 'parsemag', $count ) . "\n{$titles}" );
968 } elseif( !$wgTitle->isProtected( 'edit' ) && $wgTitle->isNamespaceProtected() ) {
969 // Namespace protection
970 global $wgNamespaceProtection;
971 $ns = $wgTitle->getNamespace() == NS_MAIN
972 ? wfMsg( 'nstab-main' )
973 : $wgTitle->getNsText();
974 $this->addWikiText( wfMsg( 'namespaceprotected', $ns ) );
975 } else {
976 // Standard protection
977 $this->addWikiText( wfMsg( 'protectedpagetext' ) );
979 } else {
980 $this->setPageTitle( wfMsg( 'readonly' ) );
981 if ( $wgReadOnly ) {
982 $reason = $wgReadOnly;
983 } else {
984 $reason = file_get_contents( $wgReadOnlyFile );
986 $this->addWikiText( wfMsg( 'readonlytext', $reason ) );
989 if( is_string( $source ) ) {
990 $this->addWikiText( wfMsg( 'viewsourcetext' ) );
991 $rows = $wgUser->getIntOption( 'rows' );
992 $cols = $wgUser->getIntOption( 'cols' );
993 $text = "\n<textarea name='wpTextbox1' id='wpTextbox1' cols='$cols' rows='$rows' readonly='readonly'>" .
994 htmlspecialchars( $source ) . "\n</textarea>";
995 $this->addHTML( $text );
997 $article = new Article( $wgTitle );
998 $this->addHTML( $skin->formatTemplates( $article->getUsedTemplates() ) );
1000 $this->returnToMain( false );
1003 /** @deprecated */
1004 public function fatalError( $message ) {
1005 throw new FatalError( $message );
1008 /** @deprecated */
1009 public function unexpectedValueError( $name, $val ) {
1010 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1013 /** @deprecated */
1014 public function fileCopyError( $old, $new ) {
1015 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1018 /** @deprecated */
1019 public function fileRenameError( $old, $new ) {
1020 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1023 /** @deprecated */
1024 public function fileDeleteError( $name ) {
1025 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1028 /** @deprecated */
1029 public function fileNotFoundError( $name ) {
1030 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1033 public function showFatalError( $message ) {
1034 $this->setPageTitle( wfMsg( "internalerror" ) );
1035 $this->setRobotpolicy( "noindex,nofollow" );
1036 $this->setArticleRelated( false );
1037 $this->enableClientCache( false );
1038 $this->mRedirect = '';
1039 $this->mBodytext = $message;
1042 public function showUnexpectedValueError( $name, $val ) {
1043 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1046 public function showFileCopyError( $old, $new ) {
1047 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1050 public function showFileRenameError( $old, $new ) {
1051 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1054 public function showFileDeleteError( $name ) {
1055 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1058 public function showFileNotFoundError( $name ) {
1059 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1063 * Add a "return to" link pointing to a specified title
1065 * @param Title $title Title to link
1067 public function addReturnTo( $title ) {
1068 global $wgUser;
1069 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1070 $this->addHtml( "<p>{$link}</p>\n" );
1074 * Add a "return to" link pointing to a specified title,
1075 * or the title indicated in the request, or else the main page
1077 * @param null $unused No longer used
1078 * @param Title $returnto Title to return to
1080 public function returnToMain( $unused = null, $returnto = NULL ) {
1081 global $wgRequest;
1083 if ( $returnto == NULL ) {
1084 $returnto = $wgRequest->getText( 'returnto' );
1087 if ( '' === $returnto ) {
1088 $returnto = Title::newMainPage();
1091 if ( is_object( $returnto ) ) {
1092 $titleObj = $returnto;
1093 } else {
1094 $titleObj = Title::newFromText( $returnto );
1096 if ( !is_object( $titleObj ) ) {
1097 $titleObj = Title::newMainPage();
1100 $this->addReturnTo( $titleObj );
1104 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1105 * and uses the first 10 of them for META keywords
1107 * @param ParserOutput &$parserOutput
1109 private function addKeywords( &$parserOutput ) {
1110 global $wgTitle;
1111 $this->addKeyword( $wgTitle->getPrefixedText() );
1112 $count = 1;
1113 $links2d =& $parserOutput->getLinks();
1114 if ( !is_array( $links2d ) ) {
1115 return;
1117 foreach ( $links2d as $dbkeys ) {
1118 foreach( $dbkeys as $dbkey => $unused ) {
1119 $this->addKeyword( $dbkey );
1120 if ( ++$count > 10 ) {
1121 break 2;
1128 * @return string The doctype, opening <html>, and head element.
1130 public function headElement() {
1131 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1132 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1133 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1135 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1136 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1137 } else {
1138 $ret = '';
1141 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1143 if ( '' == $this->getHTMLTitle() ) {
1144 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1147 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1148 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1149 foreach($wgXhtmlNamespaces as $tag => $ns) {
1150 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1152 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1153 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1154 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
1156 $ret .= $this->getHeadLinks();
1157 global $wgStylePath;
1158 if( $this->isPrintable() ) {
1159 $media = '';
1160 } else {
1161 $media = "media='print'";
1163 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1164 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1166 $sk = $wgUser->getSkin();
1167 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1168 $ret .= $this->mScripts;
1169 $ret .= $sk->getUserStyles();
1170 $ret .= $this->getHeadItems();
1172 if ($wgUseTrackbacks && $this->isArticleRelated())
1173 $ret .= $wgTitle->trackbackRDF();
1175 $ret .= "</head>\n";
1176 return $ret;
1180 * @return string HTML tag links to be put in the header.
1182 public function getHeadLinks() {
1183 global $wgRequest;
1184 $ret = '';
1185 foreach ( $this->mMetatags as $tag ) {
1186 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1187 $a = 'http-equiv';
1188 $tag[0] = substr( $tag[0], 5 );
1189 } else {
1190 $a = 'name';
1192 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
1195 $p = $this->mRobotpolicy;
1196 if( $p !== '' && $p != 'index,follow' ) {
1197 // http://www.robotstxt.org/wc/meta-user.html
1198 // Only show if it's different from the default robots policy
1199 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
1202 if ( count( $this->mKeywords ) > 0 ) {
1203 $strip = array(
1204 "/<.*?>/" => '',
1205 "/_/" => ' '
1207 $ret .= "\t\t<meta name=\"keywords\" content=\"" .
1208 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
1210 foreach ( $this->mLinktags as $tag ) {
1211 $ret .= "\t\t<link";
1212 foreach( $tag as $attr => $val ) {
1213 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
1215 $ret .= " />\n";
1217 if( $this->isSyndicated() ) {
1218 # FIXME: centralize the mime-type and name information in Feed.php
1219 $link = $wgRequest->escapeAppendQuery( 'feed=rss' );
1220 $ret .= "<link rel='alternate' type='application/rss+xml' title='RSS 2.0' href='$link' />\n";
1221 $link = $wgRequest->escapeAppendQuery( 'feed=atom' );
1222 $ret .= "<link rel='alternate' type='application/atom+xml' title='Atom 1.0' href='$link' />\n";
1225 return $ret;
1229 * Turn off regular page output and return an error reponse
1230 * for when rate limiting has triggered.
1231 * @todo i18n
1233 public function rateLimited() {
1234 global $wgOut;
1235 $wgOut->disable();
1236 wfHttpError( 500, 'Internal Server Error',
1237 'Sorry, the server has encountered an internal error. ' .
1238 'Please wait a moment and hit "refresh" to submit the request again.' );
1242 * Show an "add new section" link?
1244 * @return bool True if the parser output instructs us to add one
1246 public function showNewSectionLink() {
1247 return $this->mNewSectionLink;
1251 * Show a warning about slave lag
1253 * If the lag is higher than 30 seconds, then the warning is
1254 * a bit more obvious
1256 * @param int $lag Slave lag
1258 public function showLagWarning( $lag ) {
1259 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1261 if ($lag < $wgSlaveLagWarning)
1262 return;
1264 $message = ($lag >= $wgSlaveLagCritical) ? 'lag-warn-high' : 'lag-warn-normal';
1265 $warning = wfMsgHtml( $message, htmlspecialchars( $lag ) );
1266 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );