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