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