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