Introducing $wgFeed variable. Allows tuning sydication feeds off, when desired.
[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 $mFeedLinksAppendQuery = false;
27 var $mEnableClientCache = true;
28 var $mArticleBodyOnly = false;
29
30 var $mNewSectionLink = false;
31 var $mNoGallery = false;
32 var $mPageTitleActionText = '';
33 var $mParseWarnings = array();
34
35 /**
36 * Constructor
37 * Initialise private variables
38 */
39 function __construct() {
40 global $wgAllowUserJs;
41 $this->mAllowUserJs = $wgAllowUserJs;
42 $this->mMetatags = $this->mKeywords = $this->mLinktags = array();
43 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
44 $this->mRedirect = $this->mLastModified =
45 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
46 $this->mOnloadHandler = $this->mPageLinkTitle = '';
47 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
48 $this->mSuppressQuickbar = $this->mPrintable = false;
49 $this->mLanguageLinks = array();
50 $this->mCategoryLinks = array();
51 $this->mDoNothing = false;
52 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
53 $this->mParserOptions = null;
54 $this->mSquidMaxage = 0;
55 $this->mScripts = '';
56 $this->mHeadItems = array();
57 $this->mETag = false;
58 $this->mRevisionId = null;
59 $this->mNewSectionLink = false;
60 $this->mTemplateIds = array();
61 }
62
63 public function redirect( $url, $responsecode = '302' ) {
64 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
65 $this->mRedirect = str_replace( "\n", '', $url );
66 $this->mRedirectCode = $responsecode;
67 }
68
69 public function getRedirect() {
70 return $this->mRedirect;
71 }
72
73 /**
74 * Set the HTTP status code to send with the output.
75 *
76 * @param int $statusCode
77 * @return nothing
78 */
79 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
80
81 # To add an http-equiv meta tag, precede the name with "http:"
82 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
83 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
84 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
85 function addStyle( $style ) {
86 global $wgStylePath, $wgStyleVersion;
87 $this->addLink(
88 array(
89 'rel' => 'stylesheet',
90 'href' => $wgStylePath . '/' . $style . '?' . $wgStyleVersion ) );
91 }
92
93 /**
94 * Add a self-contained script tag with the given contents
95 * @param string $script JavaScript text, no <script> tags
96 */
97 function addInlineScript( $script ) {
98 global $wgJsMimeType;
99 $this->mScripts .= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
100 }
101
102 function getScript() {
103 return $this->mScripts . $this->getHeadItems();
104 }
105
106 function getHeadItems() {
107 $s = '';
108 foreach ( $this->mHeadItems as $item ) {
109 $s .= $item;
110 }
111 return $s;
112 }
113
114 function addHeadItem( $name, $value ) {
115 $this->mHeadItems[$name] = $value;
116 }
117
118 function hasHeadItem( $name ) {
119 return isset( $this->mHeadItems[$name] );
120 }
121
122 function setETag($tag) { $this->mETag = $tag; }
123 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
124 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
125
126 function addLink( $linkarr ) {
127 # $linkarr should be an associative array of attributes. We'll escape on output.
128 array_push( $this->mLinktags, $linkarr );
129 }
130
131 function addMetadataLink( $linkarr ) {
132 # note: buggy CC software only reads first "meta" link
133 static $haveMeta = false;
134 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
135 $this->addLink( $linkarr );
136 $haveMeta = true;
137 }
138
139 /**
140 * checkLastModified tells the client to use the client-cached page if
141 * possible. If sucessful, the OutputPage is disabled so that
142 * any future call to OutputPage->output() have no effect.
143 *
144 * @return bool True iff cache-ok headers was sent.
145 */
146 function checkLastModified ( $timestamp ) {
147 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
148 $fname = 'OutputPage::checkLastModified';
149
150 if ( !$timestamp || $timestamp == '19700101000000' ) {
151 wfDebug( "$fname: CACHE DISABLED, NO TIMESTAMP\n" );
152 return;
153 }
154 if( !$wgCachePages ) {
155 wfDebug( "$fname: CACHE DISABLED\n", false );
156 return;
157 }
158 if( $wgUser->getOption( 'nocache' ) ) {
159 wfDebug( "$fname: USER DISABLED CACHE\n", false );
160 return;
161 }
162
163 $timestamp=wfTimestamp(TS_MW,$timestamp);
164 $lastmod = wfTimestamp( TS_RFC2822, max( $timestamp, $wgUser->mTouched, $wgCacheEpoch ) );
165
166 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
167 # IE sends sizes after the date like this:
168 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
169 # this breaks strtotime().
170 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
171
172 wfSuppressWarnings(); // E_STRICT system time bitching
173 $modsinceTime = strtotime( $modsince );
174 wfRestoreWarnings();
175
176 $ismodsince = wfTimestamp( TS_MW, $modsinceTime ? $modsinceTime : 1 );
177 wfDebug( "$fname: -- client send If-Modified-Since: " . $modsince . "\n", false );
178 wfDebug( "$fname: -- we might send Last-Modified : $lastmod\n", false );
179 if( ($ismodsince >= $timestamp ) && $wgUser->validateCache( $ismodsince ) && $ismodsince >= $wgCacheEpoch ) {
180 # Make sure you're in a place you can leave when you call us!
181 $wgRequest->response()->header( "HTTP/1.0 304 Not Modified" );
182 $this->mLastModified = $lastmod;
183 $this->sendCacheControl();
184 wfDebug( "$fname: CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
185 $this->disable();
186
187 // Don't output a compressed blob when using ob_gzhandler;
188 // it's technically against HTTP spec and seems to confuse
189 // Firefox when the response gets split over two packets.
190 wfClearOutputBuffers();
191
192 return true;
193 } else {
194 wfDebug( "$fname: READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
195 $this->mLastModified = $lastmod;
196 }
197 } else {
198 wfDebug( "$fname: client did not send If-Modified-Since header\n", false );
199 $this->mLastModified = $lastmod;
200 }
201 }
202
203 function setPageTitleActionText( $text ) {
204 $this->mPageTitleActionText = $text;
205 }
206
207 function getPageTitleActionText () {
208 if ( isset( $this->mPageTitleActionText ) ) {
209 return $this->mPageTitleActionText;
210 }
211 }
212
213 public function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
214 public function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
215 public function setPageTitle( $name ) {
216 global $action, $wgContLang;
217 $name = $wgContLang->convert($name, true);
218 $this->mPagetitle = $name;
219 if(!empty($action)) {
220 $taction = $this->getPageTitleActionText();
221 if( !empty( $taction ) ) {
222 $name .= ' - '.$taction;
223 }
224 }
225
226 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
227 }
228 public function getHTMLTitle() { return $this->mHTMLtitle; }
229 public function getPageTitle() { return $this->mPagetitle; }
230 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
231 public function getSubtitle() { return $this->mSubtitle; }
232 public function isArticle() { return $this->mIsarticle; }
233 public function setPrintable() { $this->mPrintable = true; }
234 public function isPrintable() { return $this->mPrintable; }
235 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
236 public function isSyndicated() { return $this->mShowFeedLinks; }
237 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
238 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
239 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
240 public function getOnloadHandler() { return $this->mOnloadHandler; }
241 public function disable() { $this->mDoNothing = true; }
242
243 public function setArticleRelated( $v ) {
244 $this->mIsArticleRelated = $v;
245 if ( !$v ) {
246 $this->mIsarticle = false;
247 }
248 }
249 public function setArticleFlag( $v ) {
250 $this->mIsarticle = $v;
251 if ( $v ) {
252 $this->mIsArticleRelated = $v;
253 }
254 }
255
256 public function isArticleRelated() { return $this->mIsArticleRelated; }
257
258 public function getLanguageLinks() { return $this->mLanguageLinks; }
259 public function addLanguageLinks($newLinkArray) {
260 $this->mLanguageLinks += $newLinkArray;
261 }
262 public function setLanguageLinks($newLinkArray) {
263 $this->mLanguageLinks = $newLinkArray;
264 }
265
266 public function getCategoryLinks() {
267 return $this->mCategoryLinks;
268 }
269
270 /**
271 * Add an array of categories, with names in the keys
272 */
273 public function addCategoryLinks( $categories ) {
274 global $wgUser, $wgContLang;
275
276 if ( !is_array( $categories ) ) {
277 return;
278 }
279 if ( count( $categories ) == 0 ) {
280 return;
281 }
282 # Add the links to a LinkBatch
283 $arr = array( NS_CATEGORY => $categories );
284 $lb = new LinkBatch;
285 $lb->setArray( $arr );
286
287 # Fetch existence plus the hiddencat property
288 $dbr = wfGetDB( DB_SLAVE );
289 $pageTable = $dbr->tableName( 'page' );
290 $propsTable = $dbr->tableName( 'page_props' );
291 $where = $lb->constructSet( 'page', $dbr );
292 $sql = "SELECT page_id, page_namespace, page_title, pp_value FROM $pageTable LEFT JOIN $propsTable " .
293 " ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
294 $res = $dbr->query( $sql, __METHOD__ );
295
296 # Add the results to the link cache
297 $lb->addResultToCache( LinkCache::singleton(), $res );
298
299 # Remove categories with hiddencat
300 foreach ( $res as $row ) {
301 if ( isset( $row->pp_value ) ) {
302 unset( $categories[$row->page_title] );
303 }
304 }
305
306 # Add the remaining categories to the skin
307 $sk = $wgUser->getSkin();
308 foreach ( $categories as $category => $unused ) {
309 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
310 $text = $wgContLang->convertHtml( $title->getText() );
311 $this->mCategoryLinks[] = $sk->makeLinkObj( $title, $text );
312 }
313 }
314
315 public function setCategoryLinks($categories) {
316 $this->mCategoryLinks = array();
317 $this->addCategoryLinks($categories);
318 }
319
320 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
321 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
322
323 public function disallowUserJs() { $this->mAllowUserJs = false; }
324 public function isUserJsAllowed() { return $this->mAllowUserJs; }
325
326 public function addHTML( $text ) { $this->mBodytext .= $text; }
327 public function clearHTML() { $this->mBodytext = ''; }
328 public function getHTML() { return $this->mBodytext; }
329 public function debug( $text ) { $this->mDebugtext .= $text; }
330
331 /* @deprecated */
332 public function setParserOptions( $options ) {
333 return $this->parserOptions( $options );
334 }
335
336 public function parserOptions( $options = null ) {
337 if ( !$this->mParserOptions ) {
338 $this->mParserOptions = new ParserOptions;
339 }
340 return wfSetVar( $this->mParserOptions, $options );
341 }
342
343 /**
344 * Set the revision ID which will be seen by the wiki text parser
345 * for things such as embedded {{REVISIONID}} variable use.
346 * @param mixed $revid an integer, or NULL
347 * @return mixed previous value
348 */
349 public function setRevisionId( $revid ) {
350 $val = is_null( $revid ) ? null : intval( $revid );
351 return wfSetVar( $this->mRevisionId, $val );
352 }
353
354 /**
355 * Convert wikitext to HTML and add it to the buffer
356 * Default assumes that the current page title will
357 * be used.
358 *
359 * @param string $text
360 * @param bool $linestart
361 */
362 public function addWikiText( $text, $linestart = true ) {
363 global $wgTitle;
364 $this->addWikiTextTitle($text, $wgTitle, $linestart);
365 }
366
367 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
368 $this->addWikiTextTitle($text, $title, $linestart);
369 }
370
371 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
372 $this->addWikiTextTitle( $text, $title, $linestart, true );
373 }
374
375 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
376 global $wgParser;
377
378 $fname = 'OutputPage:addWikiTextTitle';
379 wfProfileIn($fname);
380
381 wfIncrStats('pcache_not_possible');
382
383 $popts = $this->parserOptions();
384 $oldTidy = $popts->setTidy($tidy);
385
386 $parserOutput = $wgParser->parse( $text, $title, $popts,
387 $linestart, true, $this->mRevisionId );
388
389 $popts->setTidy( $oldTidy );
390
391 $this->addParserOutput( $parserOutput );
392
393 wfProfileOut($fname);
394 }
395
396 /**
397 * @todo document
398 * @param ParserOutput object &$parserOutput
399 */
400 public function addParserOutputNoText( &$parserOutput ) {
401 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
402 $this->addCategoryLinks( $parserOutput->getCategories() );
403 $this->mNewSectionLink = $parserOutput->getNewSection();
404 $this->addKeywords( $parserOutput );
405 $this->mParseWarnings = $parserOutput->getWarnings();
406 if ( $parserOutput->getCacheTime() == -1 ) {
407 $this->enableClientCache( false );
408 }
409 $this->mNoGallery = $parserOutput->getNoGallery();
410 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
411 // Versioning...
412 $this->mTemplateIds += (array)$parserOutput->mTemplateIds;
413
414 // Display title
415 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
416 $this->setPageTitle( $dt );
417
418 // Hooks registered in the object
419 global $wgParserOutputHooks;
420 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
421 list( $hookName, $data ) = $hookInfo;
422 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
423 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
424 }
425 }
426
427 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
428 }
429
430 /**
431 * @todo document
432 * @param ParserOutput &$parserOutput
433 */
434 function addParserOutput( &$parserOutput ) {
435 $this->addParserOutputNoText( $parserOutput );
436 $text = $parserOutput->getText();
437 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
438 $this->addHTML( $text );
439 }
440
441 /**
442 * Add wikitext to the buffer, assuming that this is the primary text for a page view
443 * Saves the text into the parser cache if possible.
444 *
445 * @param string $text
446 * @param Article $article
447 * @param bool $cache
448 * @deprecated Use Article::outputWikitext
449 */
450 public function addPrimaryWikiText( $text, $article, $cache = true ) {
451 global $wgParser, $wgUser;
452
453 $popts = $this->parserOptions();
454 $popts->setTidy(true);
455 $parserOutput = $wgParser->parse( $text, $article->mTitle,
456 $popts, true, true, $this->mRevisionId );
457 $popts->setTidy(false);
458 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
459 $parserCache =& ParserCache::singleton();
460 $parserCache->save( $parserOutput, $article, $wgUser );
461 }
462
463 $this->addParserOutput( $parserOutput );
464 }
465
466 /**
467 * @deprecated use addWikiTextTidy()
468 */
469 public function addSecondaryWikiText( $text, $linestart = true ) {
470 global $wgTitle;
471 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
472 }
473
474 /**
475 * Add wikitext with tidy enabled
476 */
477 public function addWikiTextTidy( $text, $linestart = true ) {
478 global $wgTitle;
479 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
480 }
481
482
483 /**
484 * Add the output of a QuickTemplate to the output buffer
485 *
486 * @param QuickTemplate $template
487 */
488 public function addTemplate( &$template ) {
489 ob_start();
490 $template->execute();
491 $this->addHTML( ob_get_contents() );
492 ob_end_clean();
493 }
494
495 /**
496 * Parse wikitext and return the HTML.
497 *
498 * @param string $text
499 * @param bool $linestart Is this the start of a line?
500 * @param bool $interface ??
501 */
502 public function parse( $text, $linestart = true, $interface = false ) {
503 global $wgParser, $wgTitle;
504 $popts = $this->parserOptions();
505 if ( $interface) { $popts->setInterfaceMessage(true); }
506 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
507 $linestart, true, $this->mRevisionId );
508 if ( $interface) { $popts->setInterfaceMessage(false); }
509 return $parserOutput->getText();
510 }
511
512 /**
513 * @param Article $article
514 * @param User $user
515 *
516 * @return bool True if successful, else false.
517 */
518 public function tryParserCache( &$article, $user ) {
519 $parserCache =& ParserCache::singleton();
520 $parserOutput = $parserCache->get( $article, $user );
521 if ( $parserOutput !== false ) {
522 $this->addParserOutput( $parserOutput );
523 return true;
524 } else {
525 return false;
526 }
527 }
528
529 /**
530 * @param int $maxage Maximum cache time on the Squid, in seconds.
531 */
532 public function setSquidMaxage( $maxage ) {
533 $this->mSquidMaxage = $maxage;
534 }
535
536 /**
537 * Use enableClientCache(false) to force it to send nocache headers
538 * @param $state ??
539 */
540 public function enableClientCache( $state ) {
541 return wfSetVar( $this->mEnableClientCache, $state );
542 }
543
544 function getCacheVaryCookies() {
545 global $wgCookiePrefix;
546 return array(
547 "{$wgCookiePrefix}Token",
548 "{$wgCookiePrefix}LoggedOut",
549 session_name() );
550 }
551
552 function uncacheableBecauseRequestVars() {
553 global $wgRequest;
554 return $wgRequest->getText('useskin', false) === false
555 && $wgRequest->getText('uselang', false) === false;
556 }
557
558 /**
559 * Check if the request has a cache-varying cookie header
560 * If it does, it's very important that we don't allow public caching
561 */
562 function haveCacheVaryCookies() {
563 global $wgRequest, $wgCookiePrefix;
564 $cookieHeader = $wgRequest->getHeader( 'cookie' );
565 if ( $cookieHeader === false ) {
566 return false;
567 }
568 $cvCookies = $this->getCacheVaryCookies();
569 foreach ( $cvCookies as $cookieName ) {
570 # Check for a simple string match, like the way squid does it
571 if ( strpos( $cookieHeader, $cookieName ) ) {
572 wfDebug( __METHOD__.": found $cookieName\n" );
573 return true;
574 }
575 }
576 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
577 return false;
578 }
579
580 /** Get a complete X-Vary-Options header */
581 public function getXVO() {
582 global $wgCookiePrefix;
583 $cvCookies = $this->getCacheVaryCookies();
584 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
585 $first = true;
586 foreach ( $cvCookies as $cookieName ) {
587 if ( $first ) {
588 $first = false;
589 } else {
590 $xvo .= ';';
591 }
592 $xvo .= 'string-contains=' . $cookieName;
593 }
594 return $xvo;
595 }
596
597 public function sendCacheControl() {
598 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
599 $fname = 'OutputPage::sendCacheControl';
600
601 $response = $wgRequest->response();
602 if ($wgUseETag && $this->mETag)
603 $response->header("ETag: $this->mETag");
604
605 # don't serve compressed data to clients who can't handle it
606 # maintain different caches for logged-in users and non-logged in ones
607 $response->header( 'Vary: Accept-Encoding, Cookie' );
608
609 # Add an X-Vary-Options header for Squid with Wikimedia patches
610 $response->header( $this->getXVO() );
611
612 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
613 if( $wgUseSquid && session_id() == '' &&
614 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
615 {
616 if ( $wgUseESI ) {
617 # We'll purge the proxy cache explicitly, but require end user agents
618 # to revalidate against the proxy on each visit.
619 # Surrogate-Control controls our Squid, Cache-Control downstream caches
620 wfDebug( "$fname: proxy caching with ESI; {$this->mLastModified} **\n", false );
621 # start with a shorter timeout for initial testing
622 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
623 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
624 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
625 } else {
626 # We'll purge the proxy cache for anons explicitly, but require end user agents
627 # to revalidate against the proxy on each visit.
628 # IMPORTANT! The Squid needs to replace the Cache-Control header with
629 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
630 wfDebug( "$fname: local proxy caching; {$this->mLastModified} **\n", false );
631 # start with a shorter timeout for initial testing
632 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
633 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
634 }
635 } else {
636 # We do want clients to cache if they can, but they *must* check for updates
637 # on revisiting the page.
638 wfDebug( "$fname: private caching; {$this->mLastModified} **\n", false );
639 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
640 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
641 }
642 if($this->mLastModified) $response->header( "Last-modified: {$this->mLastModified}" );
643 } else {
644 wfDebug( "$fname: no caching **\n", false );
645
646 # In general, the absence of a last modified header should be enough to prevent
647 # the client from using its cache. We send a few other things just to make sure.
648 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
649 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
650 $response->header( 'Pragma: no-cache' );
651 }
652 }
653
654 /**
655 * Finally, all the text has been munged and accumulated into
656 * the object, let's actually output it:
657 */
658 public function output() {
659 global $wgUser, $wgOutputEncoding, $wgRequest;
660 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
661 global $wgJsMimeType, $wgStylePath, $wgUseAjax, $wgAjaxSearch, $wgAjaxWatch;
662 global $wgServer, $wgStyleVersion;
663
664 if( $this->mDoNothing ){
665 return;
666 }
667 $fname = 'OutputPage::output';
668 wfProfileIn( $fname );
669
670 if ( '' != $this->mRedirect ) {
671 # Standards require redirect URLs to be absolute
672 $this->mRedirect = wfExpandUrl( $this->mRedirect );
673 if( $this->mRedirectCode == '301') {
674 if( !$wgDebugRedirects ) {
675 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
676 }
677 $this->mLastModified = wfTimestamp( TS_RFC2822 );
678 }
679
680 $this->sendCacheControl();
681
682 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
683 if( $wgDebugRedirects ) {
684 $url = htmlspecialchars( $this->mRedirect );
685 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
686 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
687 print "</body>\n</html>\n";
688 } else {
689 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
690 }
691 wfProfileOut( $fname );
692 return;
693 }
694 elseif ( $this->mStatusCode )
695 {
696 $statusMessage = array(
697 100 => 'Continue',
698 101 => 'Switching Protocols',
699 102 => 'Processing',
700 200 => 'OK',
701 201 => 'Created',
702 202 => 'Accepted',
703 203 => 'Non-Authoritative Information',
704 204 => 'No Content',
705 205 => 'Reset Content',
706 206 => 'Partial Content',
707 207 => 'Multi-Status',
708 300 => 'Multiple Choices',
709 301 => 'Moved Permanently',
710 302 => 'Found',
711 303 => 'See Other',
712 304 => 'Not Modified',
713 305 => 'Use Proxy',
714 307 => 'Temporary Redirect',
715 400 => 'Bad Request',
716 401 => 'Unauthorized',
717 402 => 'Payment Required',
718 403 => 'Forbidden',
719 404 => 'Not Found',
720 405 => 'Method Not Allowed',
721 406 => 'Not Acceptable',
722 407 => 'Proxy Authentication Required',
723 408 => 'Request Timeout',
724 409 => 'Conflict',
725 410 => 'Gone',
726 411 => 'Length Required',
727 412 => 'Precondition Failed',
728 413 => 'Request Entity Too Large',
729 414 => 'Request-URI Too Large',
730 415 => 'Unsupported Media Type',
731 416 => 'Request Range Not Satisfiable',
732 417 => 'Expectation Failed',
733 422 => 'Unprocessable Entity',
734 423 => 'Locked',
735 424 => 'Failed Dependency',
736 500 => 'Internal Server Error',
737 501 => 'Not Implemented',
738 502 => 'Bad Gateway',
739 503 => 'Service Unavailable',
740 504 => 'Gateway Timeout',
741 505 => 'HTTP Version Not Supported',
742 507 => 'Insufficient Storage'
743 );
744
745 if ( $statusMessage[$this->mStatusCode] )
746 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
747 }
748
749 $sk = $wgUser->getSkin();
750
751 if ( $wgUseAjax ) {
752 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajax.js?$wgStyleVersion\"></script>\n" );
753
754 wfRunHooks( 'AjaxAddScript', array( &$this ) );
755
756 if( $wgAjaxSearch && $wgUser->getBoolOption( 'ajaxsearch' ) ) {
757 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxsearch.js?$wgStyleVersion\"></script>\n" );
758 $this->addScript( "<script type=\"{$wgJsMimeType}\">hookEvent(\"load\", sajax_onload);</script>\n" );
759 }
760
761 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
762 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxwatch.js?$wgStyleVersion\"></script>\n" );
763 }
764 }
765
766
767
768 # Buffer output; final headers may depend on later processing
769 ob_start();
770
771 # Disable temporary placeholders, so that the skin produces HTML
772 $sk->postParseLinkColour( false );
773
774 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
775 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
776
777 if ($this->mArticleBodyOnly) {
778 $this->out($this->mBodytext);
779 } else {
780 wfProfileIn( 'Output-skin' );
781 $sk->outputPage( $this );
782 wfProfileOut( 'Output-skin' );
783 }
784
785 $this->sendCacheControl();
786 ob_end_flush();
787 wfProfileOut( $fname );
788 }
789
790 /**
791 * @todo document
792 * @param string $ins
793 */
794 public function out( $ins ) {
795 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
796 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
797 $outs = $ins;
798 } else {
799 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
800 if ( false === $outs ) { $outs = $ins; }
801 }
802 print $outs;
803 }
804
805 /**
806 * @todo document
807 */
808 public static function setEncodings() {
809 global $wgInputEncoding, $wgOutputEncoding;
810 global $wgUser, $wgContLang;
811
812 $wgInputEncoding = strtolower( $wgInputEncoding );
813
814 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
815 $wgOutputEncoding = strtolower( $wgOutputEncoding );
816 return;
817 }
818 $wgOutputEncoding = $wgInputEncoding;
819 }
820
821 /**
822 * Deprecated, use wfReportTime() instead.
823 * @return string
824 * @deprecated
825 */
826 public function reportTime() {
827 $time = wfReportTime();
828 return $time;
829 }
830
831 /**
832 * Produce a "user is blocked" page.
833 *
834 * @param bool $return Whether to have a "return to $wgTitle" message or not.
835 * @return nothing
836 */
837 function blockedPage( $return = true ) {
838 global $wgUser, $wgContLang, $wgTitle, $wgLang;
839
840 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
841 $this->setRobotpolicy( 'noindex,nofollow' );
842 $this->setArticleRelated( false );
843
844 $name = User::whoIs( $wgUser->blockedBy() );
845 $reason = $wgUser->blockedFor();
846 if( $reason == '' ) {
847 $reason = wfMsg( 'blockednoreason' );
848 }
849 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
850 $ip = wfGetIP();
851
852 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
853
854 $blockid = $wgUser->mBlock->mId;
855
856 $blockExpiry = $wgUser->mBlock->mExpiry;
857 if ( $blockExpiry == 'infinity' ) {
858 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
859 // Search for localization in 'ipboptions'
860 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
861 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
862 if ( strpos( $option, ":" ) === false )
863 continue;
864 list( $show, $value ) = explode( ":", $option );
865 if ( $value == 'infinite' || $value == 'indefinite' ) {
866 $blockExpiry = $show;
867 break;
868 }
869 }
870 } else {
871 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
872 }
873
874 if ( $wgUser->mBlock->mAuto ) {
875 $msg = 'autoblockedtext';
876 } else {
877 $msg = 'blockedtext';
878 }
879
880 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
881 * This could be a username, an ip range, or a single ip. */
882 $intended = $wgUser->mBlock->mAddress;
883
884 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
885
886 # Don't auto-return to special pages
887 if( $return ) {
888 $return = $wgTitle->getNamespace() > -1 ? $wgTitle->getPrefixedText() : NULL;
889 $this->returnToMain( false, $return );
890 }
891 }
892
893 /**
894 * Output a standard error page
895 *
896 * @param string $title Message key for page title
897 * @param string $msg Message key for page text
898 * @param array $params Message parameters
899 */
900 public function showErrorPage( $title, $msg, $params = array() ) {
901 global $wgTitle;
902 if ( isset($wgTitle) ) {
903 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
904 }
905 $this->setPageTitle( wfMsg( $title ) );
906 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
907 $this->setRobotpolicy( 'noindex,nofollow' );
908 $this->setArticleRelated( false );
909 $this->enableClientCache( false );
910 $this->mRedirect = '';
911 $this->mBodytext = '';
912
913 array_unshift( $params, 'parse' );
914 array_unshift( $params, $msg );
915 $this->addHtml( call_user_func_array( 'wfMsgExt', $params ) );
916
917 $this->returnToMain( false );
918 }
919
920 /**
921 * Output a standard permission error page
922 *
923 * @param array $errors Error message keys
924 */
925 public function showPermissionsErrorPage( $errors )
926 {
927 global $wgTitle;
928
929 $this->mDebugtext .= 'Original title: ' .
930 $wgTitle->getPrefixedText() . "\n";
931 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
932 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
933 $this->setRobotpolicy( 'noindex,nofollow' );
934 $this->setArticleRelated( false );
935 $this->enableClientCache( false );
936 $this->mRedirect = '';
937 $this->mBodytext = '';
938 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors ) );
939 }
940
941 /** @deprecated */
942 public function errorpage( $title, $msg ) {
943 throw new ErrorPageError( $title, $msg );
944 }
945
946 /**
947 * Display an error page indicating that a given version of MediaWiki is
948 * required to use it
949 *
950 * @param mixed $version The version of MediaWiki needed to use the page
951 */
952 public function versionRequired( $version ) {
953 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
954 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
955 $this->setRobotpolicy( 'noindex,nofollow' );
956 $this->setArticleRelated( false );
957 $this->mBodytext = '';
958
959 $this->addWikiMsg( 'versionrequiredtext', $version );
960 $this->returnToMain();
961 }
962
963 /**
964 * Display an error page noting that a given permission bit is required.
965 *
966 * @param string $permission key required
967 */
968 public function permissionRequired( $permission ) {
969 global $wgGroupPermissions, $wgUser;
970
971 $this->setPageTitle( wfMsg( 'badaccess' ) );
972 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
973 $this->setRobotpolicy( 'noindex,nofollow' );
974 $this->setArticleRelated( false );
975 $this->mBodytext = '';
976
977 $groups = array();
978 foreach( $wgGroupPermissions as $key => $value ) {
979 if( isset( $value[$permission] ) && $value[$permission] == true ) {
980 $groupName = User::getGroupName( $key );
981 $groupPage = User::getGroupPage( $key );
982 if( $groupPage ) {
983 $skin = $wgUser->getSkin();
984 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
985 } else {
986 $groups[] = $groupName;
987 }
988 }
989 }
990 $n = count( $groups );
991 $groups = implode( ', ', $groups );
992 switch( $n ) {
993 case 0:
994 case 1:
995 case 2:
996 $message = wfMsgHtml( "badaccess-group$n", $groups );
997 break;
998 default:
999 $message = wfMsgHtml( 'badaccess-groups', $groups );
1000 }
1001 $this->addHtml( $message );
1002 $this->returnToMain( false );
1003 }
1004
1005 /**
1006 * Use permissionRequired.
1007 * @deprecated
1008 */
1009 public function sysopRequired() {
1010 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1011 }
1012
1013 /**
1014 * Use permissionRequired.
1015 * @deprecated
1016 */
1017 public function developerRequired() {
1018 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1019 }
1020
1021 /**
1022 * Produce the stock "please login to use the wiki" page
1023 */
1024 public function loginToUse() {
1025 global $wgUser, $wgTitle, $wgContLang;
1026
1027 if( $wgUser->isLoggedIn() ) {
1028 $this->permissionRequired( 'read' );
1029 return;
1030 }
1031
1032 $skin = $wgUser->getSkin();
1033
1034 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1035 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1036 $this->setRobotPolicy( 'noindex,nofollow' );
1037 $this->setArticleFlag( false );
1038
1039 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1040 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1041 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1042 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1043
1044 # Don't return to the main page if the user can't read it
1045 # otherwise we'll end up in a pointless loop
1046 $mainPage = Title::newMainPage();
1047 if( $mainPage->userCanRead() )
1048 $this->returnToMain( true, $mainPage );
1049 }
1050
1051 /** @deprecated */
1052 public function databaseError( $fname, $sql, $error, $errno ) {
1053 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1054 }
1055
1056 /**
1057 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1058 * @return string The wikitext error-messages, formatted into a list.
1059 */
1060 public function formatPermissionsErrorMessage( $errors ) {
1061 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1062
1063 if (count( $errors ) > 1) {
1064 $text .= '<ul class="permissions-errors">' . "\n";
1065
1066 foreach( $errors as $error )
1067 {
1068 $text .= '<li>';
1069 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1070 $text .= "</li>\n";
1071 }
1072 $text .= '</ul>';
1073 } else {
1074 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1075 }
1076
1077 return $text;
1078 }
1079
1080 /**
1081 * Display a page stating that the Wiki is in read-only mode,
1082 * and optionally show the source of the page that the user
1083 * was trying to edit. Should only be called (for this
1084 * purpose) after wfReadOnly() has returned true.
1085 *
1086 * For historical reasons, this function is _also_ used to
1087 * show the error message when a user tries to edit a page
1088 * they are not allowed to edit. (Unless it's because they're
1089 * blocked, then we show blockedPage() instead.) In this
1090 * case, the second parameter should be set to true and a list
1091 * of reasons supplied as the third parameter.
1092 *
1093 * @todo Needs to be split into multiple functions.
1094 *
1095 * @param string $source Source code to show (or null).
1096 * @param bool $protected Is this a permissions error?
1097 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1098 */
1099 public function readOnlyPage( $source = null, $protected = false, $reasons = array() ) {
1100 global $wgUser, $wgReadOnlyFile, $wgReadOnly, $wgTitle;
1101 $skin = $wgUser->getSkin();
1102
1103 $this->setRobotpolicy( 'noindex,nofollow' );
1104 $this->setArticleRelated( false );
1105
1106 // If no reason is given, just supply a default "I can't let you do
1107 // that, Dave" message. Should only occur if called by legacy code.
1108 if ( $protected && empty($reasons) ) {
1109 $reasons[] = array( 'badaccess-group0' );
1110 }
1111
1112 if ( !empty($reasons) ) {
1113 // Permissions error
1114 if( $source ) {
1115 $this->setPageTitle( wfMsg( 'viewsource' ) );
1116 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1117 } else {
1118 $this->setPageTitle( wfMsg( 'badaccess' ) );
1119 }
1120 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons ) );
1121 } else {
1122 // Wiki is read only
1123 $this->setPageTitle( wfMsg( 'readonly' ) );
1124 if ( $wgReadOnly ) {
1125 $reason = $wgReadOnly;
1126 } else {
1127 // Should not happen, user should have called wfReadOnly() first
1128 $reason = file_get_contents( $wgReadOnlyFile );
1129 }
1130 $this->addWikiMsg( 'readonlytext', $reason );
1131 }
1132
1133 // Show source, if supplied
1134 if( is_string( $source ) ) {
1135 $this->addWikiMsg( 'viewsourcetext' );
1136 $text = wfOpenElement( 'textarea',
1137 array( 'id' => 'wpTextbox1',
1138 'name' => 'wpTextbox1',
1139 'cols' => $wgUser->getOption( 'cols' ),
1140 'rows' => $wgUser->getOption( 'rows' ),
1141 'readonly' => 'readonly' ) );
1142 $text .= htmlspecialchars( $source );
1143 $text .= wfCloseElement( 'textarea' );
1144 $this->addHTML( $text );
1145
1146 // Show templates used by this article
1147 $skin = $wgUser->getSkin();
1148 $article = new Article( $wgTitle );
1149 $this->addHTML( $skin->formatTemplates( $article->getUsedTemplates() ) );
1150 }
1151
1152 # If the title doesn't exist, it's fairly pointless to print a return
1153 # link to it. After all, you just tried editing it and couldn't, so
1154 # what's there to do there?
1155 if( $wgTitle->exists() ) {
1156 $this->returnToMain( false, $wgTitle );
1157 }
1158 }
1159
1160 /** @deprecated */
1161 public function fatalError( $message ) {
1162 throw new FatalError( $message );
1163 }
1164
1165 /** @deprecated */
1166 public function unexpectedValueError( $name, $val ) {
1167 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1168 }
1169
1170 /** @deprecated */
1171 public function fileCopyError( $old, $new ) {
1172 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1173 }
1174
1175 /** @deprecated */
1176 public function fileRenameError( $old, $new ) {
1177 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1178 }
1179
1180 /** @deprecated */
1181 public function fileDeleteError( $name ) {
1182 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1183 }
1184
1185 /** @deprecated */
1186 public function fileNotFoundError( $name ) {
1187 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1188 }
1189
1190 public function showFatalError( $message ) {
1191 $this->setPageTitle( wfMsg( "internalerror" ) );
1192 $this->setRobotpolicy( "noindex,nofollow" );
1193 $this->setArticleRelated( false );
1194 $this->enableClientCache( false );
1195 $this->mRedirect = '';
1196 $this->mBodytext = $message;
1197 }
1198
1199 public function showUnexpectedValueError( $name, $val ) {
1200 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1201 }
1202
1203 public function showFileCopyError( $old, $new ) {
1204 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1205 }
1206
1207 public function showFileRenameError( $old, $new ) {
1208 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1209 }
1210
1211 public function showFileDeleteError( $name ) {
1212 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1213 }
1214
1215 public function showFileNotFoundError( $name ) {
1216 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1217 }
1218
1219 /**
1220 * Add a "return to" link pointing to a specified title
1221 *
1222 * @param Title $title Title to link
1223 */
1224 public function addReturnTo( $title ) {
1225 global $wgUser;
1226 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1227 $this->addHtml( "<p>{$link}</p>\n" );
1228 }
1229
1230 /**
1231 * Add a "return to" link pointing to a specified title,
1232 * or the title indicated in the request, or else the main page
1233 *
1234 * @param null $unused No longer used
1235 * @param Title $returnto Title to return to
1236 */
1237 public function returnToMain( $unused = null, $returnto = NULL ) {
1238 global $wgRequest;
1239
1240 if ( $returnto == NULL ) {
1241 $returnto = $wgRequest->getText( 'returnto' );
1242 }
1243
1244 if ( '' === $returnto ) {
1245 $returnto = Title::newMainPage();
1246 }
1247
1248 if ( is_object( $returnto ) ) {
1249 $titleObj = $returnto;
1250 } else {
1251 $titleObj = Title::newFromText( $returnto );
1252 }
1253 if ( !is_object( $titleObj ) ) {
1254 $titleObj = Title::newMainPage();
1255 }
1256
1257 $this->addReturnTo( $titleObj );
1258 }
1259
1260 /**
1261 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1262 * and uses the first 10 of them for META keywords
1263 *
1264 * @param ParserOutput &$parserOutput
1265 */
1266 private function addKeywords( &$parserOutput ) {
1267 global $wgTitle;
1268 $this->addKeyword( $wgTitle->getPrefixedText() );
1269 $count = 1;
1270 $links2d =& $parserOutput->getLinks();
1271 if ( !is_array( $links2d ) ) {
1272 return;
1273 }
1274 foreach ( $links2d as $dbkeys ) {
1275 foreach( $dbkeys as $dbkey => $unused ) {
1276 $this->addKeyword( $dbkey );
1277 if ( ++$count > 10 ) {
1278 break 2;
1279 }
1280 }
1281 }
1282 }
1283
1284 /**
1285 * @return string The doctype, opening <html>, and head element.
1286 */
1287 public function headElement() {
1288 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1289 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1290 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1291
1292 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1293 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1294 } else {
1295 $ret = '';
1296 }
1297
1298 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1299
1300 if ( '' == $this->getHTMLTitle() ) {
1301 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1302 }
1303
1304 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1305 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1306 foreach($wgXhtmlNamespaces as $tag => $ns) {
1307 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1308 }
1309 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1310 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1311 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
1312
1313 $ret .= $this->getHeadLinks();
1314 global $wgStylePath;
1315 if( $this->isPrintable() ) {
1316 $media = '';
1317 } else {
1318 $media = "media='print'";
1319 }
1320 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1321 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1322
1323 $sk = $wgUser->getSkin();
1324 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1325 $ret .= $this->mScripts;
1326 $ret .= $sk->getUserStyles();
1327 $ret .= $this->getHeadItems();
1328
1329 if ($wgUseTrackbacks && $this->isArticleRelated())
1330 $ret .= $wgTitle->trackbackRDF();
1331
1332 $ret .= "</head>\n";
1333 return $ret;
1334 }
1335
1336 /**
1337 * @return string HTML tag links to be put in the header.
1338 */
1339 public function getHeadLinks() {
1340 global $wgRequest, $wgFeed;
1341 $ret = '';
1342 foreach ( $this->mMetatags as $tag ) {
1343 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1344 $a = 'http-equiv';
1345 $tag[0] = substr( $tag[0], 5 );
1346 } else {
1347 $a = 'name';
1348 }
1349 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
1350 }
1351
1352 $p = $this->mRobotpolicy;
1353 if( $p !== '' && $p != 'index,follow' ) {
1354 // http://www.robotstxt.org/wc/meta-user.html
1355 // Only show if it's different from the default robots policy
1356 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
1357 }
1358
1359 if ( count( $this->mKeywords ) > 0 ) {
1360 $strip = array(
1361 "/<.*?>/" => '',
1362 "/_/" => ' '
1363 );
1364 $ret .= "\t\t<meta name=\"keywords\" content=\"" .
1365 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
1366 }
1367 foreach ( $this->mLinktags as $tag ) {
1368 $ret .= "\t\t<link";
1369 foreach( $tag as $attr => $val ) {
1370 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
1371 }
1372 $ret .= " />\n";
1373 }
1374
1375 if( $wgFeed ) {
1376 foreach( $this->getSyndicationLinks() as $format => $link ) {
1377 # Use the page name for the title (accessed through $wgTitle since
1378 # there's no other way). In principle, this could lead to issues
1379 # with having the same name for different feeds corresponding to
1380 # the same page, but we can't avoid that at this low a level.
1381 global $wgTitle;
1382
1383 $ret .= $this->feedLink(
1384 $format,
1385 $link,
1386 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1387 }
1388
1389 # Recent changes feed should appear on every page
1390 # Put it after the per-page feed to avoid changing existing behavior.
1391 # It's still available, probably via a menu in your browser.
1392 global $wgSitename;
1393 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1394 $ret .= $this->feedLink(
1395 'rss',
1396 $rctitle->getFullURL( 'feed=rss' ),
1397 wfMsg( 'site-rss-feed', $wgSitename ) );
1398 $ret .= $this->feedLink(
1399 'atom',
1400 $rctitle->getFullURL( 'feed=atom' ),
1401 wfMsg( 'site-atom-feed', $wgSitename ) );
1402 }
1403
1404 return $ret;
1405 }
1406
1407 /**
1408 * Return URLs for each supported syndication format for this page.
1409 * @return array associating format keys with URLs
1410 */
1411 public function getSyndicationLinks() {
1412 global $wgTitle, $wgFeedClasses;
1413 $links = array();
1414
1415 if( $this->isSyndicated() ) {
1416 if( is_string( $this->getFeedAppendQuery() ) ) {
1417 $appendQuery = "&" . $this->getFeedAppendQuery();
1418 } else {
1419 $appendQuery = "";
1420 }
1421
1422 foreach( $wgFeedClasses as $format => $class ) {
1423 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1424 }
1425 }
1426 return $links;
1427 }
1428
1429 /**
1430 * Generate a <link rel/> for an RSS feed.
1431 */
1432 private function feedLink( $type, $url, $text ) {
1433 return Xml::element( 'link', array(
1434 'rel' => 'alternate',
1435 'type' => "application/$type+xml",
1436 'title' => $text,
1437 'href' => $url ) ) . "\n";
1438 }
1439
1440 /**
1441 * Turn off regular page output and return an error reponse
1442 * for when rate limiting has triggered.
1443 */
1444 public function rateLimited() {
1445 global $wgOut, $wgTitle;
1446
1447 $this->setPageTitle(wfMsg('actionthrottled'));
1448 $this->setRobotPolicy( 'noindex,follow' );
1449 $this->setArticleRelated( false );
1450 $this->enableClientCache( false );
1451 $this->mRedirect = '';
1452 $this->clearHTML();
1453 $this->setStatusCode(503);
1454 $this->addWikiMsg( 'actionthrottledtext' );
1455
1456 $this->returnToMain( false, $wgTitle );
1457 }
1458
1459 /**
1460 * Show an "add new section" link?
1461 *
1462 * @return bool
1463 */
1464 public function showNewSectionLink() {
1465 return $this->mNewSectionLink;
1466 }
1467
1468 /**
1469 * Show a warning about slave lag
1470 *
1471 * If the lag is higher than $wgSlaveLagCritical seconds,
1472 * then the warning is a bit more obvious. If the lag is
1473 * lower than $wgSlaveLagWarning, then no warning is shown.
1474 *
1475 * @param int $lag Slave lag
1476 */
1477 public function showLagWarning( $lag ) {
1478 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1479 if( $lag >= $wgSlaveLagWarning ) {
1480 $message = $lag < $wgSlaveLagCritical
1481 ? 'lag-warn-normal'
1482 : 'lag-warn-high';
1483 $warning = wfMsgExt( $message, 'parse', $lag );
1484 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1485 }
1486 }
1487
1488 /**
1489 * Add a wikitext-formatted message to the output.
1490 * This is equivalent to:
1491 *
1492 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1493 */
1494 public function addWikiMsg( /*...*/ ) {
1495 $args = func_get_args();
1496 $name = array_shift( $args );
1497 $this->addWikiMsgArray( $name, $args );
1498 }
1499
1500 /**
1501 * Add a wikitext-formatted message to the output.
1502 * Like addWikiMsg() except the parameters are taken as an array
1503 * instead of a variable argument list.
1504 *
1505 * $options is passed through to wfMsgExt(), see that function for details.
1506 */
1507 public function addWikiMsgArray( $name, $args, $options = array() ) {
1508 $options[] = 'parse';
1509 $text = wfMsgExt( $name, $options, $args );
1510 $this->addHTML( $text );
1511 }
1512
1513 /**
1514 * This function takes a number of message/argument specifications, wraps them in
1515 * some overall structure, and then parses the result and adds it to the output.
1516 *
1517 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1518 * on. The subsequent arguments may either be strings, in which case they are the
1519 * message names, or an arrays, in which case the first element is the message name,
1520 * and subsequent elements are the parameters to that message.
1521 *
1522 * The special named parameter 'options' in a message specification array is passed
1523 * through to the $options parameter of wfMsgExt().
1524 *
1525 * For example:
1526 *
1527 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1528 *
1529 * Is equivalent to:
1530 *
1531 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1532 */
1533 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1534 $msgSpecs = func_get_args();
1535 array_shift( $msgSpecs );
1536 $msgSpecs = array_values( $msgSpecs );
1537 $s = $wrap;
1538 foreach ( $msgSpecs as $n => $spec ) {
1539 $options = array();
1540 if ( is_array( $spec ) ) {
1541 $args = $spec;
1542 $name = array_shift( $args );
1543 if ( isset( $args['options'] ) ) {
1544 $options = $args['options'];
1545 unset( $args['options'] );
1546 }
1547 } else {
1548 $args = array();
1549 $name = $spec;
1550 }
1551 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1552 }
1553 $this->addHTML( $this->parse( $s ) );
1554 }
1555 }