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