* Add 'charset' to Content-Type headers on various HTTP error responses
[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 $mSuppressQuickbar;
19 var $mOnloadHandler;
20 var $mDoNothing;
21 var $mContainsOldMagic, $mContainsNewMagic;
22 var $mIsArticleRelated;
23 protected $mParserOptions; // lazy initialised, use parserOptions()
24 var $mShowFeedLinks = false;
25 var $mEnableClientCache = true;
26 var $mArticleBodyOnly = false;
27
28 var $mNewSectionLink = false;
29 var $mNoGallery = false;
30
31 /**
32 * Constructor
33 * Initialise private variables
34 */
35 function __construct() {
36 $this->mMetatags = $this->mKeywords = $this->mLinktags = array();
37 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
38 $this->mRedirect = $this->mLastModified =
39 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
40 $this->mOnloadHandler = $this->mPageLinkTitle = '';
41 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
42 $this->mSuppressQuickbar = $this->mPrintable = false;
43 $this->mLanguageLinks = array();
44 $this->mCategoryLinks = array();
45 $this->mDoNothing = false;
46 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
47 $this->mParserOptions = null;
48 $this->mSquidMaxage = 0;
49 $this->mScripts = '';
50 $this->mETag = false;
51 $this->mRevisionId = null;
52 $this->mNewSectionLink = false;
53 }
54
55 public function redirect( $url, $responsecode = '302' ) {
56 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
57 $this->mRedirect = str_replace( "\n", '', $url );
58 $this->mRedirectCode = $responsecode;
59 }
60
61 /**
62 * Set the HTTP status code to send with the output.
63 *
64 * @param int $statusCode
65 * @return nothing
66 */
67 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
68
69 # To add an http-equiv meta tag, precede the name with "http:"
70 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
71 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
72 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
73
74 /**
75 * Add a self-contained script tag with the given contents
76 * @param string $script JavaScript text, no <script> tags
77 */
78 function addInlineScript( $script ) {
79 global $wgJsMimeType;
80 $this->mScripts .= "<script type=\"$wgJsMimeType\"><!--\n$script\n--></script>";
81 }
82
83 function getScript() { return $this->mScripts; }
84
85 function setETag($tag) { $this->mETag = $tag; }
86 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
87 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
88
89 function addLink( $linkarr ) {
90 # $linkarr should be an associative array of attributes. We'll escape on output.
91 array_push( $this->mLinktags, $linkarr );
92 }
93
94 function addMetadataLink( $linkarr ) {
95 # note: buggy CC software only reads first "meta" link
96 static $haveMeta = false;
97 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
98 $this->addLink( $linkarr );
99 $haveMeta = true;
100 }
101
102 /**
103 * checkLastModified tells the client to use the client-cached page if
104 * possible. If sucessful, the OutputPage is disabled so that
105 * any future call to OutputPage->output() have no effect.
106 *
107 * @return bool True iff cache-ok headers was sent.
108 */
109 function checkLastModified ( $timestamp ) {
110 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
111 $fname = 'OutputPage::checkLastModified';
112
113 if ( !$timestamp || $timestamp == '19700101000000' ) {
114 wfDebug( "$fname: CACHE DISABLED, NO TIMESTAMP\n" );
115 return;
116 }
117 if( !$wgCachePages ) {
118 wfDebug( "$fname: CACHE DISABLED\n", false );
119 return;
120 }
121 if( $wgUser->getOption( 'nocache' ) ) {
122 wfDebug( "$fname: USER DISABLED CACHE\n", false );
123 return;
124 }
125
126 $timestamp=wfTimestamp(TS_MW,$timestamp);
127 $lastmod = wfTimestamp( TS_RFC2822, max( $timestamp, $wgUser->mTouched, $wgCacheEpoch ) );
128
129 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
130 # IE sends sizes after the date like this:
131 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
132 # this breaks strtotime().
133 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
134 $modsinceTime = strtotime( $modsince );
135 $ismodsince = wfTimestamp( TS_MW, $modsinceTime ? $modsinceTime : 1 );
136 wfDebug( "$fname: -- client send If-Modified-Since: " . $modsince . "\n", false );
137 wfDebug( "$fname: -- we might send Last-Modified : $lastmod\n", false );
138 if( ($ismodsince >= $timestamp ) && $wgUser->validateCache( $ismodsince ) && $ismodsince >= $wgCacheEpoch ) {
139 # Make sure you're in a place you can leave when you call us!
140 $wgRequest->response()->header( "HTTP/1.0 304 Not Modified" );
141 $this->mLastModified = $lastmod;
142 $this->sendCacheControl();
143 wfDebug( "$fname: CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
144 $this->disable();
145
146 // Don't output a compressed blob when using ob_gzhandler;
147 // it's technically against HTTP spec and seems to confuse
148 // Firefox when the response gets split over two packets.
149 wfClearOutputBuffers();
150
151 return true;
152 } else {
153 wfDebug( "$fname: READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
154 $this->mLastModified = $lastmod;
155 }
156 } else {
157 wfDebug( "$fname: client did not send If-Modified-Since header\n", false );
158 $this->mLastModified = $lastmod;
159 }
160 }
161
162 function getPageTitleActionText () {
163 global $action;
164 switch($action) {
165 case 'edit':
166 case 'delete':
167 case 'protect':
168 case 'unprotect':
169 case 'watch':
170 case 'unwatch':
171 // Display title is already customized
172 return '';
173 case 'history':
174 return wfMsg('history_short');
175 case 'submit':
176 // FIXME: bug 2735; not correct for special pages etc
177 return wfMsg('preview');
178 case 'info':
179 return wfMsg('info_short');
180 default:
181 return '';
182 }
183 }
184
185 public function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
186 public function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
187 public function setPageTitle( $name ) {
188 global $action, $wgContLang;
189 $name = $wgContLang->convert($name, true);
190 $this->mPagetitle = $name;
191 if(!empty($action)) {
192 $taction = $this->getPageTitleActionText();
193 if( !empty( $taction ) ) {
194 $name .= ' - '.$taction;
195 }
196 }
197
198 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
199 }
200 public function getHTMLTitle() { return $this->mHTMLtitle; }
201 public function getPageTitle() { return $this->mPagetitle; }
202 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
203 public function getSubtitle() { return $this->mSubtitle; }
204 public function isArticle() { return $this->mIsarticle; }
205 public function setPrintable() { $this->mPrintable = true; }
206 public function isPrintable() { return $this->mPrintable; }
207 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
208 public function isSyndicated() { return $this->mShowFeedLinks; }
209 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
210 public function getOnloadHandler() { return $this->mOnloadHandler; }
211 public function disable() { $this->mDoNothing = true; }
212
213 public function setArticleRelated( $v ) {
214 $this->mIsArticleRelated = $v;
215 if ( !$v ) {
216 $this->mIsarticle = false;
217 }
218 }
219 public function setArticleFlag( $v ) {
220 $this->mIsarticle = $v;
221 if ( $v ) {
222 $this->mIsArticleRelated = $v;
223 }
224 }
225
226 public function isArticleRelated() { return $this->mIsArticleRelated; }
227
228 public function getLanguageLinks() { return $this->mLanguageLinks; }
229 public function addLanguageLinks($newLinkArray) {
230 $this->mLanguageLinks += $newLinkArray;
231 }
232 public function setLanguageLinks($newLinkArray) {
233 $this->mLanguageLinks = $newLinkArray;
234 }
235
236 public function getCategoryLinks() {
237 return $this->mCategoryLinks;
238 }
239
240 /**
241 * Add an array of categories, with names in the keys
242 */
243 public function addCategoryLinks($categories) {
244 global $wgUser, $wgContLang;
245
246 if ( !is_array( $categories ) ) {
247 return;
248 }
249 # Add the links to the link cache in a batch
250 $arr = array( NS_CATEGORY => $categories );
251 $lb = new LinkBatch;
252 $lb->setArray( $arr );
253 $lb->execute();
254
255 $sk = $wgUser->getSkin();
256 foreach ( $categories as $category => $unused ) {
257 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
258 $text = $wgContLang->convertHtml( $title->getText() );
259 $this->mCategoryLinks[] = $sk->makeLinkObj( $title, $text );
260 }
261 }
262
263 public function setCategoryLinks($categories) {
264 $this->mCategoryLinks = array();
265 $this->addCategoryLinks($categories);
266 }
267
268 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
269 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
270
271 public function addHTML( $text ) { $this->mBodytext .= $text; }
272 public function clearHTML() { $this->mBodytext = ''; }
273 public function getHTML() { return $this->mBodytext; }
274 public function debug( $text ) { $this->mDebugtext .= $text; }
275
276 /* @deprecated */
277 public function setParserOptions( $options ) {
278 return $this->parserOptions( $options );
279 }
280
281 public function parserOptions( $options = null ) {
282 if ( !$this->mParserOptions ) {
283 $this->mParserOptions = new ParserOptions;
284 }
285 return wfSetVar( $this->mParserOptions, $options );
286 }
287
288 /**
289 * Set the revision ID which will be seen by the wiki text parser
290 * for things such as embedded {{REVISIONID}} variable use.
291 * @param mixed $revid an integer, or NULL
292 * @return mixed previous value
293 */
294 public function setRevisionId( $revid ) {
295 $val = is_null( $revid ) ? null : intval( $revid );
296 return wfSetVar( $this->mRevisionId, $val );
297 }
298
299 /**
300 * Convert wikitext to HTML and add it to the buffer
301 * Default assumes that the current page title will
302 * be used.
303 *
304 * @param string $text
305 * @param bool $linestart
306 */
307 public function addWikiText( $text, $linestart = true ) {
308 global $wgTitle;
309 $this->addWikiTextTitle($text, $wgTitle, $linestart);
310 }
311
312 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
313 $this->addWikiTextTitle($text, $title, $linestart);
314 }
315
316 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
317 $this->addWikiTextTitle( $text, $title, $linestart, true );
318 }
319
320 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
321 global $wgParser;
322
323 $fname = 'OutputPage:addWikiTextTitle';
324 wfProfileIn($fname);
325
326 wfIncrStats('pcache_not_possible');
327
328 $popts = $this->parserOptions();
329 $popts->setTidy($tidy);
330
331 $parserOutput = $wgParser->parse( $text, $title, $popts,
332 $linestart, true, $this->mRevisionId );
333
334 $this->addParserOutput( $parserOutput );
335
336 wfProfileOut($fname);
337 }
338
339 /**
340 * @todo document
341 * @param ParserOutput object &$parserOutput
342 */
343 public function addParserOutputNoText( &$parserOutput ) {
344 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
345 $this->addCategoryLinks( $parserOutput->getCategories() );
346 $this->mNewSectionLink = $parserOutput->getNewSection();
347 $this->addKeywords( $parserOutput );
348 if ( $parserOutput->getCacheTime() == -1 ) {
349 $this->enableClientCache( false );
350 }
351 if ( $parserOutput->mHTMLtitle != "" ) {
352 $this->mPagetitle = $parserOutput->mHTMLtitle ;
353 }
354 if ( $parserOutput->mSubtitle != '' ) {
355 $this->mSubtitle .= $parserOutput->mSubtitle ;
356 }
357 $this->mNoGallery = $parserOutput->getNoGallery();
358 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
359 }
360
361 /**
362 * @todo document
363 * @param ParserOutput &$parserOutput
364 */
365 function addParserOutput( &$parserOutput ) {
366 $this->addParserOutputNoText( $parserOutput );
367 $text = $parserOutput->getText();
368 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
369 $this->addHTML( $text );
370 }
371
372 /**
373 * Add wikitext to the buffer, assuming that this is the primary text for a page view
374 * Saves the text into the parser cache if possible.
375 *
376 * @param string $text
377 * @param Article $article
378 * @param bool $cache
379 * @deprecated Use Article::outputWikitext
380 */
381 public function addPrimaryWikiText( $text, $article, $cache = true ) {
382 global $wgParser, $wgUser;
383
384 $popts = $this->parserOptions();
385 $popts->setTidy(true);
386 $parserOutput = $wgParser->parse( $text, $article->mTitle,
387 $popts, true, true, $this->mRevisionId );
388 $popts->setTidy(false);
389 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
390 $parserCache =& ParserCache::singleton();
391 $parserCache->save( $parserOutput, $article, $wgUser );
392 }
393
394 $this->addParserOutput( $parserOutput );
395 }
396
397 /**
398 * @deprecated use addWikiTextTidy()
399 */
400 public function addSecondaryWikiText( $text, $linestart = true ) {
401 global $wgTitle;
402 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
403 }
404
405 /**
406 * Add wikitext with tidy enabled
407 */
408 public function addWikiTextTidy( $text, $linestart = true ) {
409 global $wgTitle;
410 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
411 }
412
413
414 /**
415 * Add the output of a QuickTemplate to the output buffer
416 *
417 * @param QuickTemplate $template
418 */
419 public function addTemplate( &$template ) {
420 ob_start();
421 $template->execute();
422 $this->addHTML( ob_get_contents() );
423 ob_end_clean();
424 }
425
426 /**
427 * Parse wikitext and return the HTML.
428 *
429 * @param string $text
430 * @param bool $linestart Is this the start of a line?
431 * @param bool $interface ??
432 */
433 public function parse( $text, $linestart = true, $interface = false ) {
434 global $wgParser, $wgTitle;
435 $popts = $this->parserOptions();
436 if ( $interface) { $popts->setInterfaceMessage(true); }
437 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
438 $linestart, true, $this->mRevisionId );
439 if ( $interface) { $popts->setInterfaceMessage(false); }
440 return $parserOutput->getText();
441 }
442
443 /**
444 * @param Article $article
445 * @param User $user
446 *
447 * @return bool True if successful, else false.
448 */
449 public function tryParserCache( &$article, $user ) {
450 $parserCache =& ParserCache::singleton();
451 $parserOutput = $parserCache->get( $article, $user );
452 if ( $parserOutput !== false ) {
453 $this->addParserOutput( $parserOutput );
454 return true;
455 } else {
456 return false;
457 }
458 }
459
460 /**
461 * @param int $maxage Maximum cache time on the Squid, in seconds.
462 */
463 public function setSquidMaxage( $maxage ) {
464 $this->mSquidMaxage = $maxage;
465 }
466
467 /**
468 * Use enableClientCache(false) to force it to send nocache headers
469 * @param $state ??
470 */
471 public function enableClientCache( $state ) {
472 return wfSetVar( $this->mEnableClientCache, $state );
473 }
474
475 function uncacheableBecauseRequestvars() {
476 global $wgRequest;
477 return $wgRequest->getText('useskin', false) === false
478 && $wgRequest->getText('uselang', false) === false;
479 }
480
481 public function sendCacheControl() {
482 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
483 $fname = 'OutputPage::sendCacheControl';
484
485 if ($wgUseETag && $this->mETag)
486 $wgRequest->response()->header("ETag: $this->mETag");
487
488 # don't serve compressed data to clients who can't handle it
489 # maintain different caches for logged-in users and non-logged in ones
490 $wgRequest->response()->header( 'Vary: Accept-Encoding, Cookie' );
491 if( !$this->uncacheableBecauseRequestvars() && $this->mEnableClientCache ) {
492 if( $wgUseSquid && session_id() == '' &&
493 ! $this->isPrintable() && $this->mSquidMaxage != 0 )
494 {
495 if ( $wgUseESI ) {
496 # We'll purge the proxy cache explicitly, but require end user agents
497 # to revalidate against the proxy on each visit.
498 # Surrogate-Control controls our Squid, Cache-Control downstream caches
499 wfDebug( "$fname: proxy caching with ESI; {$this->mLastModified} **\n", false );
500 # start with a shorter timeout for initial testing
501 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
502 $wgRequest->response()->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
503 $wgRequest->response()->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
504 } else {
505 # We'll purge the proxy cache for anons explicitly, but require end user agents
506 # to revalidate against the proxy on each visit.
507 # IMPORTANT! The Squid needs to replace the Cache-Control header with
508 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
509 wfDebug( "$fname: local proxy caching; {$this->mLastModified} **\n", false );
510 # start with a shorter timeout for initial testing
511 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
512 $wgRequest->response()->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
513 }
514 } else {
515 # We do want clients to cache if they can, but they *must* check for updates
516 # on revisiting the page.
517 wfDebug( "$fname: private caching; {$this->mLastModified} **\n", false );
518 $wgRequest->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
519 $wgRequest->response()->header( "Cache-Control: private, must-revalidate, max-age=0" );
520 }
521 if($this->mLastModified) $wgRequest->response()->header( "Last-modified: {$this->mLastModified}" );
522 } else {
523 wfDebug( "$fname: no caching **\n", false );
524
525 # In general, the absence of a last modified header should be enough to prevent
526 # the client from using its cache. We send a few other things just to make sure.
527 $wgRequest->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
528 $wgRequest->response()->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
529 $wgRequest->response()->header( 'Pragma: no-cache' );
530 }
531 }
532
533 /**
534 * Finally, all the text has been munged and accumulated into
535 * the object, let's actually output it:
536 */
537 public function output() {
538 global $wgUser, $wgOutputEncoding, $wgRequest;
539 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
540 global $wgJsMimeType, $wgStylePath, $wgUseAjax, $wgAjaxSearch, $wgAjaxWatch;
541 global $wgServer, $wgStyleVersion;
542
543 if( $this->mDoNothing ){
544 return;
545 }
546 $fname = 'OutputPage::output';
547 wfProfileIn( $fname );
548 $sk = $wgUser->getSkin();
549
550 if ( $wgUseAjax ) {
551 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajax.js?$wgStyleVersion\"></script>\n" );
552
553 wfRunHooks( 'AjaxAddScript', array( &$this ) );
554
555 if( $wgAjaxSearch ) {
556 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxsearch.js?$wgStyleVersion\"></script>\n" );
557 $this->addScript( "<script type=\"{$wgJsMimeType}\">hookEvent(\"load\", sajax_onload);</script>\n" );
558 }
559
560 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
561 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxwatch.js?$wgStyleVersion\"></script>\n" );
562 }
563 }
564
565 if ( '' != $this->mRedirect ) {
566 if( substr( $this->mRedirect, 0, 4 ) != 'http' ) {
567 # Standards require redirect URLs to be absolute
568 global $wgServer;
569 $this->mRedirect = $wgServer . $this->mRedirect;
570 }
571 if( $this->mRedirectCode == '301') {
572 if( !$wgDebugRedirects ) {
573 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
574 }
575 $this->mLastModified = wfTimestamp( TS_RFC2822 );
576 }
577
578 $this->sendCacheControl();
579
580 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
581 if( $wgDebugRedirects ) {
582 $url = htmlspecialchars( $this->mRedirect );
583 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
584 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
585 print "</body>\n</html>\n";
586 } else {
587 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
588 }
589 wfProfileOut( $fname );
590 return;
591 }
592 elseif ( $this->mStatusCode )
593 {
594 $statusMessage = array(
595 100 => 'Continue',
596 101 => 'Switching Protocols',
597 102 => 'Processing',
598 200 => 'OK',
599 201 => 'Created',
600 202 => 'Accepted',
601 203 => 'Non-Authoritative Information',
602 204 => 'No Content',
603 205 => 'Reset Content',
604 206 => 'Partial Content',
605 207 => 'Multi-Status',
606 300 => 'Multiple Choices',
607 301 => 'Moved Permanently',
608 302 => 'Found',
609 303 => 'See Other',
610 304 => 'Not Modified',
611 305 => 'Use Proxy',
612 307 => 'Temporary Redirect',
613 400 => 'Bad Request',
614 401 => 'Unauthorized',
615 402 => 'Payment Required',
616 403 => 'Forbidden',
617 404 => 'Not Found',
618 405 => 'Method Not Allowed',
619 406 => 'Not Acceptable',
620 407 => 'Proxy Authentication Required',
621 408 => 'Request Timeout',
622 409 => 'Conflict',
623 410 => 'Gone',
624 411 => 'Length Required',
625 412 => 'Precondition Failed',
626 413 => 'Request Entity Too Large',
627 414 => 'Request-URI Too Large',
628 415 => 'Unsupported Media Type',
629 416 => 'Request Range Not Satisfiable',
630 417 => 'Expectation Failed',
631 422 => 'Unprocessable Entity',
632 423 => 'Locked',
633 424 => 'Failed Dependency',
634 500 => 'Internal Server Error',
635 501 => 'Not Implemented',
636 502 => 'Bad Gateway',
637 503 => 'Service Unavailable',
638 504 => 'Gateway Timeout',
639 505 => 'HTTP Version Not Supported',
640 507 => 'Insufficient Storage'
641 );
642
643 if ( $statusMessage[$this->mStatusCode] )
644 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
645 }
646
647 # Buffer output; final headers may depend on later processing
648 ob_start();
649
650 # Disable temporary placeholders, so that the skin produces HTML
651 $sk->postParseLinkColour( false );
652
653 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
654 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
655
656 if ($this->mArticleBodyOnly) {
657 $this->out($this->mBodytext);
658 } else {
659 wfProfileIn( 'Output-skin' );
660 $sk->outputPage( $this );
661 wfProfileOut( 'Output-skin' );
662 }
663
664 $this->sendCacheControl();
665 ob_end_flush();
666 wfProfileOut( $fname );
667 }
668
669 /**
670 * @todo document
671 * @param string $ins
672 */
673 public function out( $ins ) {
674 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
675 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
676 $outs = $ins;
677 } else {
678 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
679 if ( false === $outs ) { $outs = $ins; }
680 }
681 print $outs;
682 }
683
684 /**
685 * @todo document
686 */
687 public static function setEncodings() {
688 global $wgInputEncoding, $wgOutputEncoding;
689 global $wgUser, $wgContLang;
690
691 $wgInputEncoding = strtolower( $wgInputEncoding );
692
693 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
694 $wgOutputEncoding = strtolower( $wgOutputEncoding );
695 return;
696 }
697 $wgOutputEncoding = $wgInputEncoding;
698 }
699
700 /**
701 * Deprecated, use wfReportTime() instead.
702 * @return string
703 * @deprecated
704 */
705 public function reportTime() {
706 $time = wfReportTime();
707 return $time;
708 }
709
710 /**
711 * Produce a "user is blocked" page.
712 *
713 * @param bool $return Whether to have a "return to $wgTitle" message or not.
714 * @return nothing
715 */
716 function blockedPage( $return = true ) {
717 global $wgUser, $wgContLang, $wgTitle;
718
719 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
720 $this->setRobotpolicy( 'noindex,nofollow' );
721 $this->setArticleRelated( false );
722
723 $id = $wgUser->blockedBy();
724 $reason = $wgUser->blockedFor();
725 $ip = wfGetIP();
726
727 if ( is_numeric( $id ) ) {
728 $name = User::whoIs( $id );
729 } else {
730 $name = $id;
731 }
732 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
733
734 $blockid = $wgUser->mBlock->mId;
735
736 $this->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name, $blockid ) );
737
738 # Don't auto-return to special pages
739 if( $return ) {
740 $return = $wgTitle->getNamespace() > -1 ? $wgTitle->getPrefixedText() : NULL;
741 $this->returnToMain( false, $return );
742 }
743 }
744
745 /**
746 * Outputs a pretty page to explain why the request exploded.
747 *
748 * @param string $title Message key for page title.
749 * @param string $msg Message key for page text.
750 * @return nothing
751 */
752 public function showErrorPage( $title, $msg ) {
753 global $wgTitle;
754
755 $this->mDebugtext .= 'Original title: ' .
756 $wgTitle->getPrefixedText() . "\n";
757 $this->setPageTitle( wfMsg( $title ) );
758 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
759 $this->setRobotpolicy( 'noindex,nofollow' );
760 $this->setArticleRelated( false );
761 $this->enableClientCache( false );
762 $this->mRedirect = '';
763
764 $this->mBodytext = '';
765 $this->addWikiText( wfMsg( $msg ) );
766 $this->returnToMain( false );
767 }
768
769 /** @obsolete */
770 public function errorpage( $title, $msg ) {
771 throw new ErrorPageError( $title, $msg );
772 }
773
774 /**
775 * Display an error page indicating that a given version of MediaWiki is
776 * required to use it
777 *
778 * @param mixed $version The version of MediaWiki needed to use the page
779 */
780 public function versionRequired( $version ) {
781 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
782 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
783 $this->setRobotpolicy( 'noindex,nofollow' );
784 $this->setArticleRelated( false );
785 $this->mBodytext = '';
786
787 $this->addWikiText( wfMsg( 'versionrequiredtext', $version ) );
788 $this->returnToMain();
789 }
790
791 /**
792 * Display an error page noting that a given permission bit is required.
793 *
794 * @param string $permission key required
795 */
796 public function permissionRequired( $permission ) {
797 global $wgGroupPermissions, $wgUser;
798
799 $this->setPageTitle( wfMsg( 'badaccess' ) );
800 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
801 $this->setRobotpolicy( 'noindex,nofollow' );
802 $this->setArticleRelated( false );
803 $this->mBodytext = '';
804
805 $groups = array();
806 foreach( $wgGroupPermissions as $key => $value ) {
807 if( isset( $value[$permission] ) && $value[$permission] == true ) {
808 $groupName = User::getGroupName( $key );
809 $groupPage = User::getGroupPage( $key );
810 if( $groupPage ) {
811 $skin = $wgUser->getSkin();
812 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
813 } else {
814 $groups[] = $groupName;
815 }
816 }
817 }
818 $n = count( $groups );
819 $groups = implode( ', ', $groups );
820 switch( $n ) {
821 case 0:
822 case 1:
823 case 2:
824 $message = wfMsgHtml( "badaccess-group$n", $groups );
825 break;
826 default:
827 $message = wfMsgHtml( 'badaccess-groups', $groups );
828 }
829 $this->addHtml( $message );
830 $this->returnToMain( false );
831 }
832
833 /**
834 * Use permissionRequired.
835 * @deprecated
836 */
837 public function sysopRequired() {
838 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
839 }
840
841 /**
842 * Use permissionRequired.
843 * @deprecated
844 */
845 public function developerRequired() {
846 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
847 }
848
849 /**
850 * Produce the stock "please login to use the wiki" page
851 */
852 public function loginToUse() {
853 global $wgUser, $wgTitle, $wgContLang;
854
855 if( $wgUser->isLoggedIn() ) {
856 $this->permissionRequired( 'read' );
857 return;
858 }
859
860 $skin = $wgUser->getSkin();
861
862 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
863 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
864 $this->setRobotPolicy( 'noindex,nofollow' );
865 $this->setArticleFlag( false );
866
867 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
868 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
869 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
870 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
871
872 # Don't return to the main page if the user can't read it
873 # otherwise we'll end up in a pointless loop
874 $mainPage = Title::newMainPage();
875 if( $mainPage->userCanRead() )
876 $this->returnToMain( true, $mainPage );
877 }
878
879 /** @obsolete */
880 public function databaseError( $fname, $sql, $error, $errno ) {
881 throw new MWException( "OutputPage::databaseError is obsolete\n" );
882 }
883
884 /**
885 * @todo document
886 * @param bool $protected Is the reason the page can't be reached because it's protected?
887 * @param mixed $source
888 */
889 public function readOnlyPage( $source = null, $protected = false ) {
890 global $wgUser, $wgReadOnlyFile, $wgReadOnly, $wgTitle;
891 $skin = $wgUser->getSkin();
892
893 $this->setRobotpolicy( 'noindex,nofollow' );
894 $this->setArticleRelated( false );
895
896 if( $protected ) {
897 $this->setPageTitle( wfMsg( 'viewsource' ) );
898 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
899
900 $cascadeSources = $wgTitle->getCascadeProtectionSources();
901
902 # Determine if protection is due to the page being a system message
903 # and show an appropriate explanation
904 if( $wgTitle->getNamespace() == NS_MEDIAWIKI ) {
905 $this->addWikiText( wfMsg( 'protectedinterface' ) );
906 } if ( $cascadeSources && count($cascadeSources) > 0 ) {
907 $titles = '';
908
909 foreach ( $cascadeSources as $title ) {
910 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
911 }
912
913 $notice = wfMsg( 'cascadeprotected' ) . "\n$titles";
914
915 $this->addWikiText( $notice );
916 } else {
917 $this->addWikiText( wfMsg( 'protectedpagetext' ) );
918 }
919 } else {
920 $this->setPageTitle( wfMsg( 'readonly' ) );
921 if ( $wgReadOnly ) {
922 $reason = $wgReadOnly;
923 } else {
924 $reason = file_get_contents( $wgReadOnlyFile );
925 }
926 $this->addWikiText( wfMsg( 'readonlytext', $reason ) );
927 }
928
929 if( is_string( $source ) ) {
930 $this->addWikiText( wfMsg( 'viewsourcetext' ) );
931 $rows = $wgUser->getIntOption( 'rows' );
932 $cols = $wgUser->getIntOption( 'cols' );
933 $text = "\n<textarea name='wpTextbox1' id='wpTextbox1' cols='$cols' rows='$rows' readonly='readonly'>" .
934 htmlspecialchars( $source ) . "\n</textarea>";
935 $this->addHTML( $text );
936 }
937 $article = new Article($wgTitle);
938 $this->addHTML( $skin->formatTemplates($article->getUsedTemplates()) );
939
940 $this->returnToMain( false );
941 }
942
943 /** @obsolete */
944 public function fatalError( $message ) {
945 throw new FatalError( $message );
946 }
947
948 /** @obsolete */
949 public function unexpectedValueError( $name, $val ) {
950 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
951 }
952
953 /** @obsolete */
954 public function fileCopyError( $old, $new ) {
955 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
956 }
957
958 /** @obsolete */
959 public function fileRenameError( $old, $new ) {
960 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
961 }
962
963 /** @obsolete */
964 public function fileDeleteError( $name ) {
965 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
966 }
967
968 /** @obsolete */
969 public function fileNotFoundError( $name ) {
970 throw new FatalError( wfMsg( 'filenotfound', $name ) );
971 }
972
973 public function showFatalError( $message ) {
974 $this->setPageTitle( wfMsg( "internalerror" ) );
975 $this->setRobotpolicy( "noindex,nofollow" );
976 $this->setArticleRelated( false );
977 $this->enableClientCache( false );
978 $this->mRedirect = '';
979 $this->mBodytext = $message;
980 }
981
982 public function showUnexpectedValueError( $name, $val ) {
983 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
984 }
985
986 public function showFileCopyError( $old, $new ) {
987 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
988 }
989
990 public function showFileRenameError( $old, $new ) {
991 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
992 }
993
994 public function showFileDeleteError( $name ) {
995 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
996 }
997
998 public function showFileNotFoundError( $name ) {
999 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1000 }
1001
1002 /**
1003 * return from error messages or notes
1004 * @param $auto automatically redirect the user after 10 seconds
1005 * @param $returnto page title to return to. Default is Main Page.
1006 */
1007 public function returnToMain( $auto = true, $returnto = NULL ) {
1008 global $wgUser, $wgOut, $wgRequest;
1009
1010 if ( $returnto == NULL ) {
1011 $returnto = $wgRequest->getText( 'returnto' );
1012 }
1013
1014 if ( '' === $returnto ) {
1015 $returnto = Title::newMainPage();
1016 }
1017
1018 if ( is_object( $returnto ) ) {
1019 $titleObj = $returnto;
1020 } else {
1021 $titleObj = Title::newFromText( $returnto );
1022 }
1023 if ( !is_object( $titleObj ) ) {
1024 $titleObj = Title::newMainPage();
1025 }
1026
1027 $sk = $wgUser->getSkin();
1028 $link = $sk->makeLinkObj( $titleObj, '' );
1029
1030 $r = wfMsg( 'returnto', $link );
1031 if ( $auto ) {
1032 $wgOut->addMeta( 'http:Refresh', '10;url=' . $titleObj->escapeFullURL() );
1033 }
1034 $wgOut->addHTML( "\n<p>$r</p>\n" );
1035 }
1036
1037 /**
1038 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1039 * and uses the first 10 of them for META keywords
1040 *
1041 * @param ParserOutput &$parserOutput
1042 */
1043 private function addKeywords( &$parserOutput ) {
1044 global $wgTitle;
1045 $this->addKeyword( $wgTitle->getPrefixedText() );
1046 $count = 1;
1047 $links2d =& $parserOutput->getLinks();
1048 if ( !is_array( $links2d ) ) {
1049 return;
1050 }
1051 foreach ( $links2d as $dbkeys ) {
1052 foreach( $dbkeys as $dbkey => $unused ) {
1053 $this->addKeyword( $dbkey );
1054 if ( ++$count > 10 ) {
1055 break 2;
1056 }
1057 }
1058 }
1059 }
1060
1061 /**
1062 * @return string The doctype, opening <html>, and head element.
1063 */
1064 public function headElement() {
1065 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1066 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1067 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1068
1069 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1070 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1071 } else {
1072 $ret = '';
1073 }
1074
1075 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1076
1077 if ( '' == $this->getHTMLTitle() ) {
1078 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1079 }
1080
1081 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1082 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1083 foreach($wgXhtmlNamespaces as $tag => $ns) {
1084 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1085 }
1086 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1087 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1088 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
1089
1090 $ret .= $this->getHeadLinks();
1091 global $wgStylePath;
1092 if( $this->isPrintable() ) {
1093 $media = '';
1094 } else {
1095 $media = "media='print'";
1096 }
1097 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1098 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1099
1100 $sk = $wgUser->getSkin();
1101 $ret .= $sk->getHeadScripts();
1102 $ret .= $this->mScripts;
1103 $ret .= $sk->getUserStyles();
1104
1105 if ($wgUseTrackbacks && $this->isArticleRelated())
1106 $ret .= $wgTitle->trackbackRDF();
1107
1108 $ret .= "</head>\n";
1109 return $ret;
1110 }
1111
1112 /**
1113 * @return string HTML tag links to be put in the header.
1114 */
1115 public function getHeadLinks() {
1116 global $wgRequest;
1117 $ret = '';
1118 foreach ( $this->mMetatags as $tag ) {
1119 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1120 $a = 'http-equiv';
1121 $tag[0] = substr( $tag[0], 5 );
1122 } else {
1123 $a = 'name';
1124 }
1125 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
1126 }
1127
1128 $p = $this->mRobotpolicy;
1129 if( $p !== '' && $p != 'index,follow' ) {
1130 // http://www.robotstxt.org/wc/meta-user.html
1131 // Only show if it's different from the default robots policy
1132 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
1133 }
1134
1135 if ( count( $this->mKeywords ) > 0 ) {
1136 $strip = array(
1137 "/<.*?>/" => '',
1138 "/_/" => ' '
1139 );
1140 $ret .= "\t\t<meta name=\"keywords\" content=\"" .
1141 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
1142 }
1143 foreach ( $this->mLinktags as $tag ) {
1144 $ret .= "\t\t<link";
1145 foreach( $tag as $attr => $val ) {
1146 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
1147 }
1148 $ret .= " />\n";
1149 }
1150 if( $this->isSyndicated() ) {
1151 # FIXME: centralize the mime-type and name information in Feed.php
1152 $link = $wgRequest->escapeAppendQuery( 'feed=rss' );
1153 $ret .= "<link rel='alternate' type='application/rss+xml' title='RSS 2.0' href='$link' />\n";
1154 $link = $wgRequest->escapeAppendQuery( 'feed=atom' );
1155 $ret .= "<link rel='alternate' type='application/atom+xml' title='Atom 1.0' href='$link' />\n";
1156 }
1157
1158 return $ret;
1159 }
1160
1161 /**
1162 * Turn off regular page output and return an error reponse
1163 * for when rate limiting has triggered.
1164 * @todo i18n
1165 */
1166 public function rateLimited() {
1167 global $wgOut;
1168 $wgOut->disable();
1169 wfHttpError( 500, 'Internal Server Error',
1170 'Sorry, the server has encountered an internal error. ' .
1171 'Please wait a moment and hit "refresh" to submit the request again.' );
1172 }
1173
1174 /**
1175 * Show an "add new section" link?
1176 *
1177 * @return bool True if the parser output instructs us to add one
1178 */
1179 public function showNewSectionLink() {
1180 return $this->mNewSectionLink;
1181 }
1182 }
1183 ?>