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