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