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