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