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