Revert r34559 and fix r34542 -- include rightclickedit.js for 'edit on right click...
[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 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
799 $this->addScriptFile( 'rightclickedit.js' );
800 }
801
802
803 # Buffer output; final headers may depend on later processing
804 ob_start();
805
806 # Disable temporary placeholders, so that the skin produces HTML
807 $sk->postParseLinkColour( false );
808
809 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
810 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
811
812 if ($this->mArticleBodyOnly) {
813 $this->out($this->mBodytext);
814 } else {
815 // Hook that allows last minute changes to the output page, e.g.
816 // adding of CSS or Javascript by extensions.
817 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
818
819 wfProfileIn( 'Output-skin' );
820 $sk->outputPage( $this );
821 wfProfileOut( 'Output-skin' );
822 }
823
824 $this->sendCacheControl();
825 ob_end_flush();
826 wfProfileOut( __METHOD__ );
827 }
828
829 /**
830 * @todo document
831 * @param string $ins
832 */
833 public function out( $ins ) {
834 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
835 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
836 $outs = $ins;
837 } else {
838 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
839 if ( false === $outs ) { $outs = $ins; }
840 }
841 print $outs;
842 }
843
844 /**
845 * @todo document
846 */
847 public static function setEncodings() {
848 global $wgInputEncoding, $wgOutputEncoding;
849 global $wgUser, $wgContLang;
850
851 $wgInputEncoding = strtolower( $wgInputEncoding );
852
853 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
854 $wgOutputEncoding = strtolower( $wgOutputEncoding );
855 return;
856 }
857 $wgOutputEncoding = $wgInputEncoding;
858 }
859
860 /**
861 * Deprecated, use wfReportTime() instead.
862 * @return string
863 * @deprecated
864 */
865 public function reportTime() {
866 wfDeprecated( __METHOD__ );
867 $time = wfReportTime();
868 return $time;
869 }
870
871 /**
872 * Produce a "user is blocked" page.
873 *
874 * @param bool $return Whether to have a "return to $wgTitle" message or not.
875 * @return nothing
876 */
877 function blockedPage( $return = true ) {
878 global $wgUser, $wgContLang, $wgTitle, $wgLang;
879
880 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
881 $this->setRobotpolicy( 'noindex,nofollow' );
882 $this->setArticleRelated( false );
883
884 $name = User::whoIs( $wgUser->blockedBy() );
885 $reason = $wgUser->blockedFor();
886 if( $reason == '' ) {
887 $reason = wfMsg( 'blockednoreason' );
888 }
889 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
890 $ip = wfGetIP();
891
892 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
893
894 $blockid = $wgUser->mBlock->mId;
895
896 $blockExpiry = $wgUser->mBlock->mExpiry;
897 if ( $blockExpiry == 'infinity' ) {
898 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
899 // Search for localization in 'ipboptions'
900 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
901 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
902 if ( strpos( $option, ":" ) === false )
903 continue;
904 list( $show, $value ) = explode( ":", $option );
905 if ( $value == 'infinite' || $value == 'indefinite' ) {
906 $blockExpiry = $show;
907 break;
908 }
909 }
910 } else {
911 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
912 }
913
914 if ( $wgUser->mBlock->mAuto ) {
915 $msg = 'autoblockedtext';
916 } else {
917 $msg = 'blockedtext';
918 }
919
920 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
921 * This could be a username, an ip range, or a single ip. */
922 $intended = $wgUser->mBlock->mAddress;
923
924 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
925
926 # Don't auto-return to special pages
927 if( $return ) {
928 $return = $wgTitle->getNamespace() > -1 ? $wgTitle : NULL;
929 $this->returnToMain( null, $return );
930 }
931 }
932
933 /**
934 * Output a standard error page
935 *
936 * @param string $title Message key for page title
937 * @param string $msg Message key for page text
938 * @param array $params Message parameters
939 */
940 public function showErrorPage( $title, $msg, $params = array() ) {
941 global $wgTitle;
942 if ( isset($wgTitle) ) {
943 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
944 }
945 $this->setPageTitle( wfMsg( $title ) );
946 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
947 $this->setRobotpolicy( 'noindex,nofollow' );
948 $this->setArticleRelated( false );
949 $this->enableClientCache( false );
950 $this->mRedirect = '';
951 $this->mBodytext = '';
952
953 array_unshift( $params, 'parse' );
954 array_unshift( $params, $msg );
955 $this->addHtml( call_user_func_array( 'wfMsgExt', $params ) );
956
957 $this->returnToMain();
958 }
959
960 /**
961 * Output a standard permission error page
962 *
963 * @param array $errors Error message keys
964 */
965 public function showPermissionsErrorPage( $errors )
966 {
967 global $wgTitle;
968
969 $this->mDebugtext .= 'Original title: ' .
970 $wgTitle->getPrefixedText() . "\n";
971 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
972 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
973 $this->setRobotpolicy( 'noindex,nofollow' );
974 $this->setArticleRelated( false );
975 $this->enableClientCache( false );
976 $this->mRedirect = '';
977 $this->mBodytext = '';
978 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors ) );
979 }
980
981 /** @deprecated */
982 public function errorpage( $title, $msg ) {
983 wfDeprecated( __METHOD__ );
984 throw new ErrorPageError( $title, $msg );
985 }
986
987 /**
988 * Display an error page indicating that a given version of MediaWiki is
989 * required to use it
990 *
991 * @param mixed $version The version of MediaWiki needed to use the page
992 */
993 public function versionRequired( $version ) {
994 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
995 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
996 $this->setRobotpolicy( 'noindex,nofollow' );
997 $this->setArticleRelated( false );
998 $this->mBodytext = '';
999
1000 $this->addWikiMsg( 'versionrequiredtext', $version );
1001 $this->returnToMain();
1002 }
1003
1004 /**
1005 * Display an error page noting that a given permission bit is required.
1006 *
1007 * @param string $permission key required
1008 */
1009 public function permissionRequired( $permission ) {
1010 global $wgGroupPermissions, $wgUser;
1011
1012 $this->setPageTitle( wfMsg( 'badaccess' ) );
1013 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1014 $this->setRobotpolicy( 'noindex,nofollow' );
1015 $this->setArticleRelated( false );
1016 $this->mBodytext = '';
1017
1018 $groups = array();
1019 foreach( $wgGroupPermissions as $key => $value ) {
1020 if( isset( $value[$permission] ) && $value[$permission] == true ) {
1021 $groupName = User::getGroupName( $key );
1022 $groupPage = User::getGroupPage( $key );
1023 if( $groupPage ) {
1024 $skin = $wgUser->getSkin();
1025 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1026 } else {
1027 $groups[] = $groupName;
1028 }
1029 }
1030 }
1031 $n = count( $groups );
1032 $groups = implode( ', ', $groups );
1033 switch( $n ) {
1034 case 0:
1035 case 1:
1036 case 2:
1037 $message = wfMsgHtml( "badaccess-group$n", $groups );
1038 break;
1039 default:
1040 $message = wfMsgHtml( 'badaccess-groups', $groups );
1041 }
1042 $this->addHtml( $message );
1043 $this->returnToMain();
1044 }
1045
1046 /**
1047 * Use permissionRequired.
1048 * @deprecated
1049 */
1050 public function sysopRequired() {
1051 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1052 }
1053
1054 /**
1055 * Use permissionRequired.
1056 * @deprecated
1057 */
1058 public function developerRequired() {
1059 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1060 }
1061
1062 /**
1063 * Produce the stock "please login to use the wiki" page
1064 */
1065 public function loginToUse() {
1066 global $wgUser, $wgTitle, $wgContLang;
1067
1068 if( $wgUser->isLoggedIn() ) {
1069 $this->permissionRequired( 'read' );
1070 return;
1071 }
1072
1073 $skin = $wgUser->getSkin();
1074
1075 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1076 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1077 $this->setRobotPolicy( 'noindex,nofollow' );
1078 $this->setArticleFlag( false );
1079
1080 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1081 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1082 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1083 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1084
1085 # Don't return to the main page if the user can't read it
1086 # otherwise we'll end up in a pointless loop
1087 $mainPage = Title::newMainPage();
1088 if( $mainPage->userCanRead() )
1089 $this->returnToMain( null, $mainPage );
1090 }
1091
1092 /** @deprecated */
1093 public function databaseError( $fname, $sql, $error, $errno ) {
1094 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1095 }
1096
1097 /**
1098 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1099 * @return string The wikitext error-messages, formatted into a list.
1100 */
1101 public function formatPermissionsErrorMessage( $errors ) {
1102 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1103
1104 if (count( $errors ) > 1) {
1105 $text .= '<ul class="permissions-errors">' . "\n";
1106
1107 foreach( $errors as $error )
1108 {
1109 $text .= '<li>';
1110 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1111 $text .= "</li>\n";
1112 }
1113 $text .= '</ul>';
1114 } else {
1115 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1116 }
1117
1118 return $text;
1119 }
1120
1121 /**
1122 * Display a page stating that the Wiki is in read-only mode,
1123 * and optionally show the source of the page that the user
1124 * was trying to edit. Should only be called (for this
1125 * purpose) after wfReadOnly() has returned true.
1126 *
1127 * For historical reasons, this function is _also_ used to
1128 * show the error message when a user tries to edit a page
1129 * they are not allowed to edit. (Unless it's because they're
1130 * blocked, then we show blockedPage() instead.) In this
1131 * case, the second parameter should be set to true and a list
1132 * of reasons supplied as the third parameter.
1133 *
1134 * @todo Needs to be split into multiple functions.
1135 *
1136 * @param string $source Source code to show (or null).
1137 * @param bool $protected Is this a permissions error?
1138 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1139 */
1140 public function readOnlyPage( $source = null, $protected = false, $reasons = array() ) {
1141 global $wgUser, $wgTitle;
1142 $skin = $wgUser->getSkin();
1143
1144 $this->setRobotpolicy( 'noindex,nofollow' );
1145 $this->setArticleRelated( false );
1146
1147 // If no reason is given, just supply a default "I can't let you do
1148 // that, Dave" message. Should only occur if called by legacy code.
1149 if ( $protected && empty($reasons) ) {
1150 $reasons[] = array( 'badaccess-group0' );
1151 }
1152
1153 if ( !empty($reasons) ) {
1154 // Permissions error
1155 if( $source ) {
1156 $this->setPageTitle( wfMsg( 'viewsource' ) );
1157 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1158 } else {
1159 $this->setPageTitle( wfMsg( 'badaccess' ) );
1160 }
1161 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons ) );
1162 } else {
1163 // Wiki is read only
1164 $this->setPageTitle( wfMsg( 'readonly' ) );
1165 $reason = wfReadOnlyReason();
1166 $this->addWikiMsg( 'readonlytext', $reason );
1167 }
1168
1169 // Show source, if supplied
1170 if( is_string( $source ) ) {
1171 $this->addWikiMsg( 'viewsourcetext' );
1172 $text = Xml::openElement( 'textarea',
1173 array( 'id' => 'wpTextbox1',
1174 'name' => 'wpTextbox1',
1175 'cols' => $wgUser->getOption( 'cols' ),
1176 'rows' => $wgUser->getOption( 'rows' ),
1177 'readonly' => 'readonly' ) );
1178 $text .= htmlspecialchars( $source );
1179 $text .= Xml::closeElement( 'textarea' );
1180 $this->addHTML( $text );
1181
1182 // Show templates used by this article
1183 $skin = $wgUser->getSkin();
1184 $article = new Article( $wgTitle );
1185 $this->addHTML( $skin->formatTemplates( $article->getUsedTemplates() ) );
1186 }
1187
1188 # If the title doesn't exist, it's fairly pointless to print a return
1189 # link to it. After all, you just tried editing it and couldn't, so
1190 # what's there to do there?
1191 if( $wgTitle->exists() ) {
1192 $this->returnToMain( null, $wgTitle );
1193 }
1194 }
1195
1196 /** @deprecated */
1197 public function fatalError( $message ) {
1198 wfDeprecated( __METHOD__ );
1199 throw new FatalError( $message );
1200 }
1201
1202 /** @deprecated */
1203 public function unexpectedValueError( $name, $val ) {
1204 wfDeprecated( __METHOD__ );
1205 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1206 }
1207
1208 /** @deprecated */
1209 public function fileCopyError( $old, $new ) {
1210 wfDeprecated( __METHOD__ );
1211 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1212 }
1213
1214 /** @deprecated */
1215 public function fileRenameError( $old, $new ) {
1216 wfDeprecated( __METHOD__ );
1217 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1218 }
1219
1220 /** @deprecated */
1221 public function fileDeleteError( $name ) {
1222 wfDeprecated( __METHOD__ );
1223 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1224 }
1225
1226 /** @deprecated */
1227 public function fileNotFoundError( $name ) {
1228 wfDeprecated( __METHOD__ );
1229 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1230 }
1231
1232 public function showFatalError( $message ) {
1233 $this->setPageTitle( wfMsg( "internalerror" ) );
1234 $this->setRobotpolicy( "noindex,nofollow" );
1235 $this->setArticleRelated( false );
1236 $this->enableClientCache( false );
1237 $this->mRedirect = '';
1238 $this->mBodytext = $message;
1239 }
1240
1241 public function showUnexpectedValueError( $name, $val ) {
1242 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1243 }
1244
1245 public function showFileCopyError( $old, $new ) {
1246 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1247 }
1248
1249 public function showFileRenameError( $old, $new ) {
1250 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1251 }
1252
1253 public function showFileDeleteError( $name ) {
1254 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1255 }
1256
1257 public function showFileNotFoundError( $name ) {
1258 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1259 }
1260
1261 /**
1262 * Add a "return to" link pointing to a specified title
1263 *
1264 * @param Title $title Title to link
1265 */
1266 public function addReturnTo( $title ) {
1267 global $wgUser;
1268 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1269 $this->addHtml( "<p>{$link}</p>\n" );
1270 }
1271
1272 /**
1273 * Add a "return to" link pointing to a specified title,
1274 * or the title indicated in the request, or else the main page
1275 *
1276 * @param null $unused No longer used
1277 * @param Title $returnto Title to return to
1278 */
1279 public function returnToMain( $unused = null, $returnto = NULL ) {
1280 global $wgRequest;
1281
1282 if ( $returnto == NULL ) {
1283 $returnto = $wgRequest->getText( 'returnto' );
1284 }
1285
1286 if ( '' === $returnto ) {
1287 $returnto = Title::newMainPage();
1288 }
1289
1290 if ( is_object( $returnto ) ) {
1291 $titleObj = $returnto;
1292 } else {
1293 $titleObj = Title::newFromText( $returnto );
1294 }
1295 if ( !is_object( $titleObj ) ) {
1296 $titleObj = Title::newMainPage();
1297 }
1298
1299 $this->addReturnTo( $titleObj );
1300 }
1301
1302 /**
1303 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1304 * and uses the first 10 of them for META keywords
1305 *
1306 * @param ParserOutput &$parserOutput
1307 */
1308 private function addKeywords( &$parserOutput ) {
1309 global $wgTitle;
1310 $this->addKeyword( $wgTitle->getPrefixedText() );
1311 $count = 1;
1312 $links2d =& $parserOutput->getLinks();
1313 if ( !is_array( $links2d ) ) {
1314 return;
1315 }
1316 foreach ( $links2d as $dbkeys ) {
1317 foreach( $dbkeys as $dbkey => $unused ) {
1318 $this->addKeyword( $dbkey );
1319 if ( ++$count > 10 ) {
1320 break 2;
1321 }
1322 }
1323 }
1324 }
1325
1326 /**
1327 * @return string The doctype, opening <html>, and head element.
1328 */
1329 public function headElement() {
1330 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1331 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1332 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1333
1334 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1335 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1336 } else {
1337 $ret = '';
1338 }
1339
1340 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1341
1342 if ( '' == $this->getHTMLTitle() ) {
1343 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1344 }
1345
1346 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1347 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1348 foreach($wgXhtmlNamespaces as $tag => $ns) {
1349 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1350 }
1351 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1352 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1353 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
1354
1355 $ret .= $this->getHeadLinks();
1356 global $wgStylePath;
1357 if( $this->isPrintable() ) {
1358 $media = '';
1359 } else {
1360 $media = "media='print'";
1361 }
1362 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1363 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1364
1365 $sk = $wgUser->getSkin();
1366 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1367 $ret .= $this->mScripts;
1368 $ret .= $sk->getUserStyles();
1369 $ret .= $this->getHeadItems();
1370
1371 if ($wgUseTrackbacks && $this->isArticleRelated())
1372 $ret .= $wgTitle->trackbackRDF();
1373
1374 $ret .= "</head>\n";
1375 return $ret;
1376 }
1377
1378 /**
1379 * @return string HTML tag links to be put in the header.
1380 */
1381 public function getHeadLinks() {
1382 global $wgRequest, $wgFeed;
1383 $ret = '';
1384 foreach ( $this->mMetatags as $tag ) {
1385 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1386 $a = 'http-equiv';
1387 $tag[0] = substr( $tag[0], 5 );
1388 } else {
1389 $a = 'name';
1390 }
1391 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
1392 }
1393
1394 $p = $this->mRobotpolicy;
1395 if( $p !== '' && $p != 'index,follow' ) {
1396 // http://www.robotstxt.org/wc/meta-user.html
1397 // Only show if it's different from the default robots policy
1398 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
1399 }
1400
1401 if ( count( $this->mKeywords ) > 0 ) {
1402 $strip = array(
1403 "/<.*?>/" => '',
1404 "/_/" => ' '
1405 );
1406 $ret .= "\t\t<meta name=\"keywords\" content=\"" .
1407 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
1408 }
1409 foreach ( $this->mLinktags as $tag ) {
1410 $ret .= "\t\t<link";
1411 foreach( $tag as $attr => $val ) {
1412 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
1413 }
1414 $ret .= " />\n";
1415 }
1416
1417 if( $wgFeed ) {
1418 foreach( $this->getSyndicationLinks() as $format => $link ) {
1419 # Use the page name for the title (accessed through $wgTitle since
1420 # there's no other way). In principle, this could lead to issues
1421 # with having the same name for different feeds corresponding to
1422 # the same page, but we can't avoid that at this low a level.
1423 global $wgTitle;
1424
1425 $ret .= $this->feedLink(
1426 $format,
1427 $link,
1428 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1429 }
1430
1431 # Recent changes feed should appear on every page
1432 # Put it after the per-page feed to avoid changing existing behavior.
1433 # It's still available, probably via a menu in your browser.
1434 global $wgSitename;
1435 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1436 $ret .= $this->feedLink(
1437 'rss',
1438 $rctitle->getFullURL( 'feed=rss' ),
1439 wfMsg( 'site-rss-feed', $wgSitename ) );
1440 $ret .= $this->feedLink(
1441 'atom',
1442 $rctitle->getFullURL( 'feed=atom' ),
1443 wfMsg( 'site-atom-feed', $wgSitename ) );
1444 }
1445
1446 return $ret;
1447 }
1448
1449 /**
1450 * Return URLs for each supported syndication format for this page.
1451 * @return array associating format keys with URLs
1452 */
1453 public function getSyndicationLinks() {
1454 global $wgTitle, $wgFeedClasses;
1455 $links = array();
1456
1457 if( $this->isSyndicated() ) {
1458 if( is_string( $this->getFeedAppendQuery() ) ) {
1459 $appendQuery = "&" . $this->getFeedAppendQuery();
1460 } else {
1461 $appendQuery = "";
1462 }
1463
1464 foreach( $wgFeedClasses as $format => $class ) {
1465 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1466 }
1467 }
1468 return $links;
1469 }
1470
1471 /**
1472 * Generate a <link rel/> for an RSS feed.
1473 */
1474 private function feedLink( $type, $url, $text ) {
1475 return Xml::element( 'link', array(
1476 'rel' => 'alternate',
1477 'type' => "application/$type+xml",
1478 'title' => $text,
1479 'href' => $url ) ) . "\n";
1480 }
1481
1482 /**
1483 * Turn off regular page output and return an error reponse
1484 * for when rate limiting has triggered.
1485 */
1486 public function rateLimited() {
1487 global $wgTitle;
1488
1489 $this->setPageTitle(wfMsg('actionthrottled'));
1490 $this->setRobotPolicy( 'noindex,follow' );
1491 $this->setArticleRelated( false );
1492 $this->enableClientCache( false );
1493 $this->mRedirect = '';
1494 $this->clearHTML();
1495 $this->setStatusCode(503);
1496 $this->addWikiMsg( 'actionthrottledtext' );
1497
1498 $this->returnToMain( null, $wgTitle );
1499 }
1500
1501 /**
1502 * Show an "add new section" link?
1503 *
1504 * @return bool
1505 */
1506 public function showNewSectionLink() {
1507 return $this->mNewSectionLink;
1508 }
1509
1510 /**
1511 * Show a warning about slave lag
1512 *
1513 * If the lag is higher than $wgSlaveLagCritical seconds,
1514 * then the warning is a bit more obvious. If the lag is
1515 * lower than $wgSlaveLagWarning, then no warning is shown.
1516 *
1517 * @param int $lag Slave lag
1518 */
1519 public function showLagWarning( $lag ) {
1520 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1521 if( $lag >= $wgSlaveLagWarning ) {
1522 $message = $lag < $wgSlaveLagCritical
1523 ? 'lag-warn-normal'
1524 : 'lag-warn-high';
1525 $warning = wfMsgExt( $message, 'parse', $lag );
1526 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1527 }
1528 }
1529
1530 /**
1531 * Add a wikitext-formatted message to the output.
1532 * This is equivalent to:
1533 *
1534 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1535 */
1536 public function addWikiMsg( /*...*/ ) {
1537 $args = func_get_args();
1538 $name = array_shift( $args );
1539 $this->addWikiMsgArray( $name, $args );
1540 }
1541
1542 /**
1543 * Add a wikitext-formatted message to the output.
1544 * Like addWikiMsg() except the parameters are taken as an array
1545 * instead of a variable argument list.
1546 *
1547 * $options is passed through to wfMsgExt(), see that function for details.
1548 */
1549 public function addWikiMsgArray( $name, $args, $options = array() ) {
1550 $options[] = 'parse';
1551 $text = wfMsgExt( $name, $options, $args );
1552 $this->addHTML( $text );
1553 }
1554
1555 /**
1556 * This function takes a number of message/argument specifications, wraps them in
1557 * some overall structure, and then parses the result and adds it to the output.
1558 *
1559 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1560 * on. The subsequent arguments may either be strings, in which case they are the
1561 * message names, or an arrays, in which case the first element is the message name,
1562 * and subsequent elements are the parameters to that message.
1563 *
1564 * The special named parameter 'options' in a message specification array is passed
1565 * through to the $options parameter of wfMsgExt().
1566 *
1567 * Don't use this for messages that are not in users interface language.
1568 *
1569 * For example:
1570 *
1571 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1572 *
1573 * Is equivalent to:
1574 *
1575 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1576 */
1577 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1578 $msgSpecs = func_get_args();
1579 array_shift( $msgSpecs );
1580 $msgSpecs = array_values( $msgSpecs );
1581 $s = $wrap;
1582 foreach ( $msgSpecs as $n => $spec ) {
1583 $options = array();
1584 if ( is_array( $spec ) ) {
1585 $args = $spec;
1586 $name = array_shift( $args );
1587 if ( isset( $args['options'] ) ) {
1588 $options = $args['options'];
1589 unset( $args['options'] );
1590 }
1591 } else {
1592 $args = array();
1593 $name = $spec;
1594 }
1595 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1596 }
1597 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
1598 }
1599 }