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