458907fbfd522253c4d6400e8f43411d62787a44
[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 * Output a standard error page
800 *
801 * @param string $title Message key for page title
802 * @param string $msg Message key for page text
803 * @param array $params Message parameters
804 */
805 public function showErrorPage( $title, $msg, $params = array() ) {
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 $this->mBodytext = '';
817
818 array_unshift( $params, $msg );
819 $message = call_user_func_array( 'wfMsg', $params );
820 $this->addWikiText( $message );
821
822 $this->returnToMain( false );
823 }
824
825 /** @deprecated */
826 public function errorpage( $title, $msg ) {
827 throw new ErrorPageError( $title, $msg );
828 }
829
830 /**
831 * Display an error page indicating that a given version of MediaWiki is
832 * required to use it
833 *
834 * @param mixed $version The version of MediaWiki needed to use the page
835 */
836 public function versionRequired( $version ) {
837 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
838 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
839 $this->setRobotpolicy( 'noindex,nofollow' );
840 $this->setArticleRelated( false );
841 $this->mBodytext = '';
842
843 $this->addWikiText( wfMsg( 'versionrequiredtext', $version ) );
844 $this->returnToMain();
845 }
846
847 /**
848 * Display an error page noting that a given permission bit is required.
849 *
850 * @param string $permission key required
851 */
852 public function permissionRequired( $permission ) {
853 global $wgGroupPermissions, $wgUser;
854
855 $this->setPageTitle( wfMsg( 'badaccess' ) );
856 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
857 $this->setRobotpolicy( 'noindex,nofollow' );
858 $this->setArticleRelated( false );
859 $this->mBodytext = '';
860
861 $groups = array();
862 foreach( $wgGroupPermissions as $key => $value ) {
863 if( isset( $value[$permission] ) && $value[$permission] == true ) {
864 $groupName = User::getGroupName( $key );
865 $groupPage = User::getGroupPage( $key );
866 if( $groupPage ) {
867 $skin = $wgUser->getSkin();
868 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
869 } else {
870 $groups[] = $groupName;
871 }
872 }
873 }
874 $n = count( $groups );
875 $groups = implode( ', ', $groups );
876 switch( $n ) {
877 case 0:
878 case 1:
879 case 2:
880 $message = wfMsgHtml( "badaccess-group$n", $groups );
881 break;
882 default:
883 $message = wfMsgHtml( 'badaccess-groups', $groups );
884 }
885 $this->addHtml( $message );
886 $this->returnToMain( false );
887 }
888
889 /**
890 * Use permissionRequired.
891 * @deprecated
892 */
893 public function sysopRequired() {
894 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
895 }
896
897 /**
898 * Use permissionRequired.
899 * @deprecated
900 */
901 public function developerRequired() {
902 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
903 }
904
905 /**
906 * Produce the stock "please login to use the wiki" page
907 */
908 public function loginToUse() {
909 global $wgUser, $wgTitle, $wgContLang;
910
911 if( $wgUser->isLoggedIn() ) {
912 $this->permissionRequired( 'read' );
913 return;
914 }
915
916 $skin = $wgUser->getSkin();
917
918 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
919 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
920 $this->setRobotPolicy( 'noindex,nofollow' );
921 $this->setArticleFlag( false );
922
923 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
924 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
925 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
926 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
927
928 # Don't return to the main page if the user can't read it
929 # otherwise we'll end up in a pointless loop
930 $mainPage = Title::newMainPage();
931 if( $mainPage->userCanRead() )
932 $this->returnToMain( true, $mainPage );
933 }
934
935 /** @deprecated */
936 public function databaseError( $fname, $sql, $error, $errno ) {
937 throw new MWException( "OutputPage::databaseError is obsolete\n" );
938 }
939
940 /**
941 * @todo document
942 * @param bool $protected Is the reason the page can't be reached because it's protected?
943 * @param mixed $source
944 */
945 public function readOnlyPage( $source = null, $protected = false ) {
946 global $wgUser, $wgReadOnlyFile, $wgReadOnly, $wgTitle;
947 $skin = $wgUser->getSkin();
948
949 $this->setRobotpolicy( 'noindex,nofollow' );
950 $this->setArticleRelated( false );
951
952 if( $protected ) {
953 $this->setPageTitle( wfMsg( 'viewsource' ) );
954 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
955
956 list( $cascadeSources, /* $restrictions */ ) = $wgTitle->getCascadeProtectionSources();
957
958 # Determine if protection is due to the page being a system message
959 # and show an appropriate explanation
960 if( $wgTitle->getNamespace() == NS_MEDIAWIKI ) {
961 $this->addWikiText( wfMsg( 'protectedinterface' ) );
962 } if ( $cascadeSources && count($cascadeSources) > 0 ) {
963 $titles = '';
964
965 foreach ( $cascadeSources as $title ) {
966 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
967 }
968
969 $notice = wfMsgExt( 'cascadeprotected', array('parsemag'), count($cascadeSources) ) . "\n$titles";
970
971 $this->addWikiText( $notice );
972 } else {
973 $this->addWikiText( wfMsg( 'protectedpagetext' ) );
974 }
975 } else {
976 $this->setPageTitle( wfMsg( 'readonly' ) );
977 if ( $wgReadOnly ) {
978 $reason = $wgReadOnly;
979 } else {
980 $reason = file_get_contents( $wgReadOnlyFile );
981 }
982 $this->addWikiText( wfMsg( 'readonlytext', $reason ) );
983 }
984
985 if( is_string( $source ) ) {
986 $this->addWikiText( wfMsg( 'viewsourcetext' ) );
987 $rows = $wgUser->getIntOption( 'rows' );
988 $cols = $wgUser->getIntOption( 'cols' );
989 $text = "\n<textarea name='wpTextbox1' id='wpTextbox1' cols='$cols' rows='$rows' readonly='readonly'>" .
990 htmlspecialchars( $source ) . "\n</textarea>";
991 $this->addHTML( $text );
992 }
993 $article = new Article($wgTitle);
994 $this->addHTML( $skin->formatTemplates($article->getUsedTemplates()) );
995
996 $this->returnToMain( false );
997 }
998
999 /** @deprecated */
1000 public function fatalError( $message ) {
1001 throw new FatalError( $message );
1002 }
1003
1004 /** @deprecated */
1005 public function unexpectedValueError( $name, $val ) {
1006 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1007 }
1008
1009 /** @deprecated */
1010 public function fileCopyError( $old, $new ) {
1011 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1012 }
1013
1014 /** @deprecated */
1015 public function fileRenameError( $old, $new ) {
1016 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1017 }
1018
1019 /** @deprecated */
1020 public function fileDeleteError( $name ) {
1021 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1022 }
1023
1024 /** @deprecated */
1025 public function fileNotFoundError( $name ) {
1026 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1027 }
1028
1029 public function showFatalError( $message ) {
1030 $this->setPageTitle( wfMsg( "internalerror" ) );
1031 $this->setRobotpolicy( "noindex,nofollow" );
1032 $this->setArticleRelated( false );
1033 $this->enableClientCache( false );
1034 $this->mRedirect = '';
1035 $this->mBodytext = $message;
1036 }
1037
1038 public function showUnexpectedValueError( $name, $val ) {
1039 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1040 }
1041
1042 public function showFileCopyError( $old, $new ) {
1043 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1044 }
1045
1046 public function showFileRenameError( $old, $new ) {
1047 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1048 }
1049
1050 public function showFileDeleteError( $name ) {
1051 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1052 }
1053
1054 public function showFileNotFoundError( $name ) {
1055 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1056 }
1057
1058 /**
1059 * return from error messages or notes
1060 * @param $auto automatically redirect the user after 10 seconds
1061 * @param $returnto page title to return to. Default is Main Page.
1062 */
1063 public function returnToMain( $auto = true, $returnto = NULL ) {
1064 global $wgUser, $wgOut, $wgRequest;
1065
1066 if ( $returnto == NULL ) {
1067 $returnto = $wgRequest->getText( 'returnto' );
1068 }
1069
1070 if ( '' === $returnto ) {
1071 $returnto = Title::newMainPage();
1072 }
1073
1074 if ( is_object( $returnto ) ) {
1075 $titleObj = $returnto;
1076 } else {
1077 $titleObj = Title::newFromText( $returnto );
1078 }
1079 if ( !is_object( $titleObj ) ) {
1080 $titleObj = Title::newMainPage();
1081 }
1082
1083 $sk = $wgUser->getSkin();
1084 $link = $sk->makeLinkObj( $titleObj, '' );
1085
1086 $r = wfMsg( 'returnto', $link );
1087 if ( $auto ) {
1088 $wgOut->addMeta( 'http:Refresh', '10;url=' . $titleObj->escapeFullURL() );
1089 }
1090 $wgOut->addHTML( "\n<p>$r</p>\n" );
1091 }
1092
1093 /**
1094 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1095 * and uses the first 10 of them for META keywords
1096 *
1097 * @param ParserOutput &$parserOutput
1098 */
1099 private function addKeywords( &$parserOutput ) {
1100 global $wgTitle;
1101 $this->addKeyword( $wgTitle->getPrefixedText() );
1102 $count = 1;
1103 $links2d =& $parserOutput->getLinks();
1104 if ( !is_array( $links2d ) ) {
1105 return;
1106 }
1107 foreach ( $links2d as $dbkeys ) {
1108 foreach( $dbkeys as $dbkey => $unused ) {
1109 $this->addKeyword( $dbkey );
1110 if ( ++$count > 10 ) {
1111 break 2;
1112 }
1113 }
1114 }
1115 }
1116
1117 /**
1118 * @return string The doctype, opening <html>, and head element.
1119 */
1120 public function headElement() {
1121 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1122 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1123 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1124
1125 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1126 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1127 } else {
1128 $ret = '';
1129 }
1130
1131 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1132
1133 if ( '' == $this->getHTMLTitle() ) {
1134 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1135 }
1136
1137 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1138 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1139 foreach($wgXhtmlNamespaces as $tag => $ns) {
1140 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1141 }
1142 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1143 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1144 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
1145
1146 $ret .= $this->getHeadLinks();
1147 global $wgStylePath;
1148 if( $this->isPrintable() ) {
1149 $media = '';
1150 } else {
1151 $media = "media='print'";
1152 }
1153 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1154 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1155
1156 $sk = $wgUser->getSkin();
1157 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1158 $ret .= $this->mScripts;
1159 $ret .= $sk->getUserStyles();
1160 $ret .= $this->getHeadItems();
1161
1162 if ($wgUseTrackbacks && $this->isArticleRelated())
1163 $ret .= $wgTitle->trackbackRDF();
1164
1165 $ret .= "</head>\n";
1166 return $ret;
1167 }
1168
1169 /**
1170 * @return string HTML tag links to be put in the header.
1171 */
1172 public function getHeadLinks() {
1173 global $wgRequest;
1174 $ret = '';
1175 foreach ( $this->mMetatags as $tag ) {
1176 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1177 $a = 'http-equiv';
1178 $tag[0] = substr( $tag[0], 5 );
1179 } else {
1180 $a = 'name';
1181 }
1182 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
1183 }
1184
1185 $p = $this->mRobotpolicy;
1186 if( $p !== '' && $p != 'index,follow' ) {
1187 // http://www.robotstxt.org/wc/meta-user.html
1188 // Only show if it's different from the default robots policy
1189 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
1190 }
1191
1192 if ( count( $this->mKeywords ) > 0 ) {
1193 $strip = array(
1194 "/<.*?>/" => '',
1195 "/_/" => ' '
1196 );
1197 $ret .= "\t\t<meta name=\"keywords\" content=\"" .
1198 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
1199 }
1200 foreach ( $this->mLinktags as $tag ) {
1201 $ret .= "\t\t<link";
1202 foreach( $tag as $attr => $val ) {
1203 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
1204 }
1205 $ret .= " />\n";
1206 }
1207 if( $this->isSyndicated() ) {
1208 # FIXME: centralize the mime-type and name information in Feed.php
1209 $link = $wgRequest->escapeAppendQuery( 'feed=rss' );
1210 $ret .= "<link rel='alternate' type='application/rss+xml' title='RSS 2.0' href='$link' />\n";
1211 $link = $wgRequest->escapeAppendQuery( 'feed=atom' );
1212 $ret .= "<link rel='alternate' type='application/atom+xml' title='Atom 1.0' href='$link' />\n";
1213 }
1214
1215 return $ret;
1216 }
1217
1218 /**
1219 * Turn off regular page output and return an error reponse
1220 * for when rate limiting has triggered.
1221 * @todo i18n
1222 */
1223 public function rateLimited() {
1224 global $wgOut;
1225 $wgOut->disable();
1226 wfHttpError( 500, 'Internal Server Error',
1227 'Sorry, the server has encountered an internal error. ' .
1228 'Please wait a moment and hit "refresh" to submit the request again.' );
1229 }
1230
1231 /**
1232 * Show an "add new section" link?
1233 *
1234 * @return bool True if the parser output instructs us to add one
1235 */
1236 public function showNewSectionLink() {
1237 return $this->mNewSectionLink;
1238 }
1239
1240 /**
1241 * Show a warning about slave lag
1242 *
1243 * If the lag is higher than 30 seconds, then the warning is
1244 * a bit more obvious
1245 *
1246 * @param int $lag Slave lag
1247 */
1248 public function showLagWarning( $lag ) {
1249 $message = $lag >= 30 ? 'lag-warn-high' : 'lag-warn-normal';
1250 $warning = wfMsgHtml( $message, htmlspecialchars( $lag ) );
1251 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1252 }
1253
1254 }
1255
1256 ?>